当 ggplot 中的 x 轴标签旋转时,有时会出现标签被截断的情况。
我看了这些帖子 How can I manipulate a ggplot in R to allow extra room on lhs for angle=45 long x-axis labels? 和 ggplot2 plot area margins?。两种方法中的建议是使用 plot.margin
参数。但我想知道是否有更优雅和动态的解决方案来解决这个问题。在我的应用程序中,用户将被允许更改轴标签的字体大小,因此设置硬编码值的绘图边距似乎不是一个好方法。还有其他避免这种效果的方法吗?是否可以以某种方式操纵布局?
复制代码:
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
)
)