【问题标题】:Determine the width of a ggplot2 plot area确定 ggplot2 绘图区域的宽度
【发布时间】: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 &lt;- gsub(' ', '\n', datalong$ecks)

标签: r ggplot2


【解决方案1】:

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

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

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")

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

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

【讨论】:

  • 我要使用 cowplot 解决方案。谢谢!
【解决方案2】:

您可以使用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)

【讨论】:

  • 这适用于这些数据,但我正在使用的实际数据有大约 70 行,因此包装它们并不是很方便。此外,这仍然不能使绘图区域大小相等,它只是避免了一些挤压。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2020-02-17
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多