I had very long variable names, and I managed to align them nicely by using str_wrap
. But where in this code I should apply the same method to make the plot title align?
This did not work.
scale_y_discrete(labels = function(x)str_wrap(x, width = 20))
I don't get the idea of this function(x)
.
ggplot(remove_missing(plotdata), mapping = aes(x = value, y = pct)) +
geom_col(aes(fill = value),
width = 0.30) +
scale_y_continuous(
breaks = seq(from = 0, to = 1, by = 0.2),
minor_breaks = seq(from = 0, to = 1, by = 0.1),
labels = seq(from = 0, to = 100, by = 20),
limits = c(0, 1),
expand = c(0, 0)) +
scale_fill_manual(
values = c('option1' = "blue",
'option2' = "blue",
'option3' = "blue",
'option4' = "blue",
'option5' = "blue",
'option6' = "blue"),
drop = FALSE) +
labs(x = "", y = "% of responders") +
guides(fill = "none") +
theme(
plot.margin = margin(t = 50, r = 30, b = 20, l = 5.5),
plot.title = element_text(size = 15, face = "plain"),
panel.background = element_blank(),
panel.grid.major = element_line(colour = "grey"),
panel.grid.major.x = element_blank(),
panel.grid.minor = element_line(colour = "lightgrey"),
axis.ticks.x = element_blank(),
axis.ticks.y = element_line(colour = "grey"),
axis.text.y = element_text(
size = 11,
face = "plain",
hjust = 0
),
axis.text.x = element_text(
size = 11,
face = "bold",
hjust = 0
),
axis.title.x = element_text(size = 15),
) +
coord_flip() +
ggtitle("This title is way too long and all of it does not fit into the plot, I mean it is way too long") +
scale_x_discrete(labels = function(x)
str_wrap(x, width = 20))
Data for the plot
plotdata <- structure(list(variable = c("item78", "item79", "item80", "item81",
"item82", "item83", "item84", "option1", "option1", "option2",
"option2", "option3", "option3", "option4", "option4", "option5",
"option5", "option6", "option6"), value = structure(c(NA, NA,
NA, NA, NA, NA, NA, 2L, NA, 5L, NA, 1L, NA, 3L, NA, 6L, NA, 4L,
NA), .Label = c("option3", "option1", "option4", "option6", "option2",
"option5"), class = c("ordered", "factor")), n = c(147L, 147L,
147L, 147L, 147L, 147L, 147L, 98L, 49L, 133L, 14L, 50L, 97L,
98L, 49L, 138L, 9L, 103L, 44L), pct = c(1, 1, 1, 1, 1, 1, 1,
0.666666666666667, 0.333333333333333, 0.904761904761905, 0.0952380952380952,
0.340136054421769, 0.659863945578231, 0.666666666666667, 0.333333333333333,
0.938775510204082, 0.0612244897959184, 0.700680272108844, 0.299319727891156
)), row.names = c(NA, -19L), groups = structure(list(variable = c("item78",
"item79", "item80", "item81", "item82", "item83", "item84", "option1",
"option2", "option3", "option4", "option5", "option6"), .rows = structure(list(
1L, 2L, 3L, 4L, 5L, 6L, 7L, 8:9, 10:11, 12:13, 14:15, 16:17,
18:19), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
"list"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-13L), .drop = TRUE), class = c("grouped_df", "tbl_df", "tbl",
"data.frame"))