【问题标题】:Smart association of graphs where one is faceted - ggplot2图形的智能关联,其中一个是多面的 - ggplot2
【发布时间】:2017-03-29 09:55:10
【问题描述】:

我想把这两张图结合起来:

p1 <- ggplot(iris, aes(Sepal.Length)) + 
  geom_density() + 
  facet_wrap(~ Species)

p2 <- ggplot(iris, aes(Sepal.Length)) + 
  geom_density()

要结合,我会这样做:

multiplot(p1, p2, cols = 2)

但这不是我们想要的形状。

我希望图 p2 具有与其他图相同的尺寸,并且位于最后一个分面图的旁边。

感谢帮助

【问题讨论】:

  • facet_grid(~ Species, margins = TRUE) 将在这里工作。但对于一般情况,这并不容易做到。 cowplot 包进行对齐,但您不能对齐多面图和非多面图。

标签: r ggplot2 facet facet-wrap


【解决方案1】:

不确定这是否适用于您的一般情况,但使用facet_grid 而不是facet_wrap,您可以使用margins 参数:

library(ggplot2)

ggplot(iris, aes(Sepal.Length)) + 
    geom_density() + 
    facet_grid(. ~ Species, margins = T)

如果您的问题更笼统,答案可能在于grid.arrange
这样的事情可能是一个开始:

library(gridExtra)

grid.arrange(arrangeGrob(p1, p2, 
                         widths = c(3,1), 
                         heights = c(1,20), 
                         layout_matrix = matrix(c(1,1,NA,2),2)))

如您所见,存在几个问题(不同的轴、顶部条带),但使用 grid 可能会很快变得复杂。

【讨论】:

    【解决方案2】:

    这段代码应该可以工作:

    p1 <- ggplot(iris, aes(Sepal.Length)) + 
          geom_density() + 
          ylim(limits = c(0, 1.25))+
          facet_wrap(~ Species)
    
    p2 <- ggplot(iris, aes(Sepal.Length)) + 
          geom_density() +
          ggtitle("") + # ad empty title as place holder
          labs(y = "", x = "") + # hide axis labels
          ylim(limits = c(0, 1.25)) + # y axis values should be fixed in both plots
          coord_fixed(ratio=20/1) + # ratio of x- and y-axis to reduce width of plot
          theme(axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.line.y = element_blank(),
          plot.margin=unit(c(0,0,0.65,-10), "lines")) # margin between plots = "0.65"
    

    我稍微摆弄了一下,只使用了不同的样式选项来产生这个结果。如果你有比这个更多的情节,我建议对所有人使用一个主题。

    你可以使用你已经在使用的 multiplot 函数

    multiplot(p1, p2, cols = 2)
    

    或者你安装 gridExtra 和 grid 包并使用它:

    grid.arrange(p1, p2, ncol=2) 
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2014-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      • 2011-07-21
      相关资源
      最近更新 更多