确定ggplot2绘图区域的宽度

时间:2018-08-07 22:49:18

标签: r ggplot2

我正在尝试使用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)的效果很好,但是并不精确。另外,您必须使用反复试验才能达到目标,这并不理想。有什么方法可以弄清楚实际的绘图区域是什么,以便您可以计算正确的宽度?

2 个答案:

答案 0 :(得分:3)

一种非常简单的解决方案是使用cowplot

cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")

enter image description here

自变量align允许您将绘图区域设置为相等。

或者另一个选择是在标题上添加一些分隔符:

library(stringr)

plotlong <- datalong %>%
    mutate(ecks = str_replace_all(ecks, "[[:punct:]]\\s|\\s", "\\\n")) %>% 
    ggplot(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()

cowplot::plot_grid(plotshort, plotlong, ncol = 2,align = "v")

enter image description here

如果添加中断,则可以使用grid.arrange

grid.arrange(plotshort, plotlong, ncol = 2)

enter image description here

答案 1 :(得分:0)

您可以使用stringr包装标签,并修改ggplot2脚本以在st_wrap中定义标签,并绘制为scale_x_discrete

library(stringr)    

plotshort <- ggplot(data = datashort, aes(x = ecks, y = why, width = .5)) +
  geom_bar(stat = "identity") + coord_flip() +
  scale_x_discrete(labels = str_wrap(c("Short1", "Short2", "Short3"), width = 10))  

plotlong <- ggplot(data = datalong, aes(x = ecks, y = why, width = .5)) +
    geom_bar(stat = "identity") + coord_flip() +
    scale_x_discrete(labels = str_wrap(c("Really, Really, Really, Really Long1", "Really, Really, Really, Really Long2", "Really, Really, Really, Really Long3"), width = 10))  

grid.arrange(plotshort, plotlong, ncol = 2)

enter image description here