【发布时间】:2019-01-15 02:44:32
【问题描述】:
我正在尝试使用 gridExtra 来组合两个 ggplot2 条形图(坐标翻转,以便标签占据水平空间)。问题是有些标签很短,有些标签很长。我希望左右列的宽度相同,而与标签的宽度无关。这是一个例子:
library(ggplot2)
library(gridExtra)
datashort <- data.frame(ecks = c("Short1", "Short2", "Short3"), why = c(30, 20, 40))
datalong <- data.frame(ecks = c(paste0("Really, Really, Really, Really Long", c(1:3))),
why = c(20, 30, 40))
plotshort <- ggplot(data = datashort, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()
plotlong <- ggplot(data = datalong, aes(x = ecks, y = why, width = .5)) +
geom_bar(stat = "identity") +
scale_y_continuous(breaks = c(10, 20, 30, 40, 50), limits = c(0, 50)) +
coord_flip()
grid.arrange(plotshort, plotlong, ncol = 2)
如果你这样做,你会得到一个非常宽的左侧图表和一个非常挤压的右侧图表。我知道您可以为网格排列添加宽度,但我想确切地知道它们应该是什么。在这里,widths=c(.4, .6) 看起来效果很好,但并不准确。此外,您必须通过反复试验才能到达那里,这并不理想。有什么方法可以计算出实际的绘图区域,以便计算出正确的宽度?
【问题讨论】:
-
你可以使用
egg::ggarrange -
查看这篇文章:stackoverflow.com/questions/17181051/…。此外,如果您在生成绘图之前将标签分成多行,可能会有所帮助:
datalong$ecks <- gsub(' ', '\n', datalong$ecks)