I made a custom function to make plots. To the left of the plot, I show the question, and to the right, I show the proportion of positive, neutral, and negative responses. I use map()
from the purrr
package to make each plot.
The issue is that some questions are longer than others, so even though I use str_wrap() to minimize the differences, the plots don’t neatly line up.
Is there a setting in ggplot where you can specify something to the effect of “dedicate 20% of the plot to the x-label and 80% to the plot itself and scale things accordingly to make it fit”? That way, the bars will line up.
Also open to other suggestions but it’s important that each plot prints individually. I have many plots, and I need to be able to extract just the ones I want.
Any help would be appreciated!
#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)
And here’s the function
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)
))
And here are the plots
p1 <- plots[1]
p1
p2 <- plots[2]
p2