我制作了一个自定义函数来绘制绘图。在图的左侧,我显示了问题,在右侧,我显示了积极、中性和消极反应的比例。我使用
map()
包中的 purrr
来制作每个图。
问题是有些问题比其他问题长,所以即使我使用 str_wrap() 来最小化差异,图也不会整齐地排列。
ggplot 中是否有一个设置,您可以在其中指定一些内容,以达到“将绘图的 20% 专用于 x 标签,将 80% 专用于绘图本身,并相应地缩放以使其适合”的效果?这样,条形图就会对齐。
也接受其他建议 但重要的是每个图单独打印。我有很多图,我需要能够只提取我想要的图。
如有任何帮助,我们将不胜感激!
#Sample data
library(tidyverse)
my_data <- tibble(
happiness = c("happy", "neutral", "unhappy", "happy", "neutral", "unhappy"),
percent = c(90, 5, 5, 40, 35, 25),
question = c(rep("How happy are you with your team, manager, department, and leadership at the company?", 3), rep("How happy are you with your pay?", 3)),
n = c(180, 10, 10, 80, 70, 50)
) %>%
arrange(desc(happiness), desc(percent), question)
这是函数
make_plot <- function(data){
data %>%
ggplot(aes(x = question, y = percent, fill = happiness)) +
geom_col() +
coord_flip() +
theme_minimal() +
theme(
axis.title = element_blank(),
) +
xlab(paste0(str_wrap(data$question[1], 35))) +
guides(fill="none")
}
#all questions so purrr can iterate
my_questions <- unique(my_data$question)
#create all plots
plots <- map(my_questions,
~make_plot(
my_data %>%
filter(question == .x)
))
这是情节
p1 <- plots[1]
p1
p2 <- plots[2]
p2
我在自己的工作中也遇到过类似的情况,我没有使用标签作为标题,而是使用标签作为标题,例如
library(tidyverse)
my_data <- tibble(
happiness = c("happy", "neutral", "unhappy", "happy", "neutral", "unhappy"),
percent = c(90, 5, 5, 40, 35, 25),
question = c(rep("How happy are you with your team, manager, department, and leadership at the company?", 3), rep("How happy are you with your pay?", 3)),
n = c(180, 10, 10, 80, 70, 50)
) %>%
arrange(desc(happiness), desc(percent), question)
make_plot <- function(data, title){
data %>%
ggplot(aes(x = question, y = percent, fill = happiness)) +
geom_col() +
coord_flip() +
theme_minimal() +
theme(
axis.title = element_blank(),
) +
xlab(paste0(str_wrap(data$question[1], 35))) +
guides(fill="none") +
theme(axis.text.y = element_blank(),
title = element_text(size = 8)) +
ggtitle(title)
}
#all questions so purrr can iterate
my_questions <- unique(my_data$question)
#create all plots
plots <- map(my_questions,
~make_plot(
my_data %>%
filter(question == .x),
.x
))
plots
#> [[1]]
#>
#> [[2]]
创建于 2024-04-26,使用 reprex v2.1.0
这是否适合您的用例?