When x axis labels are rotated in ggplot sometimes it happens that labels are cut off
I looked at those posts How can I manipulate a ggplot in R to allow extra room on lhs for angle=45 long x-axis labels? and ggplot2 plot area margins?. The suggestion in both cases is to use plot.margin
parameter. But I'm wondering if there's more elegant and dynamic solution to the problem. In my application users will be allowed to change font size for axes labels, so setting a hardcoded value for plot margin seems not to be a good approach. Are there any other ways to avoid such effect? Is it possible to manipulate the layout somehow?
Code to reproduce:
categories <- c(
"Entertainment",
"Research",
"Development",
"Support",
"Classic",
"Old Time"
)
years <- 2020:2021
types <- c(
"Easy",
"Pro",
"Free",
"Trial",
"Subscription"
)
d <- expand.grid(category = categories,
type = types,
year = years)
counts <- sample(0:100, size = nrow(d))
d$n <- counts
ggplot(
data = d,
aes(x = category, y = n, fill = category)
) + geom_bar(stat = "identity") +
facet_grid(rows = vars(year), cols = vars(type)) +
theme(
axis.text.x = element_text(
angle = 22.5,
hjust = 1,
size = 12
)
)