我正在尝试使用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
。 - user20650