【问题标题】:How to force multiple r plots to have the same length of x-ticks? [duplicate]如何强制多个 r 图具有相同长度的 x-ticks? [复制]
【发布时间】:2020-11-26 06:54:18
【问题描述】:

R 中的几个包能够将多个图排列成一个网格,例如gridExtracowplot。默认情况下,同一行/列中的图在其边界上对齐。下面是一个例子。三个直方图垂直排列在同一个图上。您会注意到 x-ticks 没有对齐,因此网格图看起来有点难看。

library(ggplot2);library(grid);library(cowplot)

p1 <- ggplot(data = NULL, aes(x = rt(10,19))) + 
  geom_histogram(bins = 5, fill = "darkgreen", color = "darkgrey", alpha = 0.6) +
  labs(y = "", x = "")
# similar plots for p2, p3

plot_grid(p1, textGrob("N=10"),
             p2, textGrob("N=100"),
             p3, textGrob("N=10000"),
             nrow=3, rel_widths = c(4/5, 1/5))

问题是baseggplot2 中的绘图工具不会修复x-ticks 的长度,cowplot::plot_grid 只是自动将绘图拉伸到最大宽度。一些图有更宽的 y 标签,因此它们最终会得到更短的 x-ticks。

现在我想强制三个直方图具有相同长度的 x 刻度。我想知道这种问题有什么方法/包吗?请注意,通常数据重塑结合ggplot2::facet_wrap 之类的功能应该可以解决这个问题,但我仍然想知道是否有更直接的解决方案。

【问题讨论】:

  • 阅读cowplot::plot_grid的手册,我们有对齐参数:align = c("none", "h", "v", "hv")

标签: r ggplot2 data-visualization gridextra cowplot


【解决方案1】:

我个人认为拼凑可以优雅地处理绘图的对齐方式,您可以通过将限制设置在一个共同的比例上来让绘图共享一个 x 轴。

library(ggplot2)
library(patchwork)

set.seed(123)

plots <- lapply(c(10, 100, 1000), function(n) {
  ggplot(mapping = aes(x = rt(n, 19))) +
    geom_histogram(bins = round(sqrt(n)) * 2,
                   fill = "darkgreen", colour = "darkgrey",
                   alpha = 0.6) +
    labs(y = "", x = "")
})

plots[[1]] / plots[[2]] / plots[[3]] &
  scale_x_continuous(limits = c(-5, 5),
                     oob = scales::oob_squish)

reprex package (v0.3.0) 于 2020 年 11 月 26 日创建

【讨论】:

  • 拼布是一个不错的选择。我只想指出plot_grid() 也可以对齐图,只是默认情况下不会。
【解决方案2】:

plot_grid() 函数可以对齐绘图,请参见此处:https://wilkelab.org/cowplot/articles/aligning_plots.html

library(ggplot2)
library(grid)
library(cowplot)

set.seed(123)

plots <- lapply(c(10, 100, 1000), function(n) {
  ggplot(mapping = aes(x = rt(n, 19))) +
    geom_histogram(bins = round(sqrt(n)) * 2,
                   fill = "darkgreen", colour = "darkgrey",
                   alpha = 0.6) +
    labs(y = "", x = "") +
    scale_x_continuous(
      limits = c(-5, 5),
      oob = scales::oob_squish
    )
})

plot_grid(
  plots[[1]], textGrob("N=10"),
  plots[[2]], textGrob("N=100"),
  plots[[3]], textGrob("N=10000"),
  nrow=3, rel_widths = c(4/5, 1/5), align = "v", axis = "l"
)

reprex package (v0.3.0) 于 2020 年 11 月 26 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2020-02-14
    • 2011-01-07
    • 2020-09-12
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多