【问题标题】:Controlling widths of many patchworked ggplots控制许多拼凑而成的 ggplots 的宽度
【发布时间】:2020-12-16 09:34:34
【问题描述】:

我正在尝试用多个 ggplot2 图形拼凑而成的图形。

我首先想要图 1 和 3 的共享 y 轴。然后是图 1 和 3,最后是图 2 和 4。这是我在 @Allan Cameron 的帮助下实现的 - 请参阅图。不幸的是,我无法控制情节 1、3、2 和 4 的宽度。我希望情节 1 和 3 比情节 2 和 4 更宽。此外,由于某种原因,图例最终出现在情节的中间。我怎样才能把它一直放在右边?

有什么想法吗?非常感谢所有帮助!

代码如下:


mtcars

library(ggplot2)
library(patchwork)

p1 <- ggplot(mtcars) + 
  geom_point(aes(disp, wt, colour = mpg)) + 
  ggtitle('Plot 1')

p2 <- ggplot(mtcars) + 
  geom_point(aes(carb, wt)) + 
  ggtitle('Plot 2')


p3 <- ggplot(mtcars) + 
  geom_point(aes(hp, wt, colour = mpg)) + 
  ggtitle('Plot 3')

p4 <- ggplot(mtcars) + 
  geom_area(aes(gear, carb)) + 
  ggtitle('Plot 4')


# Patchwork graph with shared y-axis
y_axis <- ggplot(data.frame(l = p1$labels$y, x = 1, y = 1)) +
  geom_text(aes(x, y, label = l), angle = 90) + 
  theme_void() +
  coord_cartesian(clip = "off")

p1$labels$y <- p2$labels$y <- " "

y_axis + (p1 + p2) / (p3 + p4) + plot_layout(widths = c(1, 15, 5), guides = "collect")


【问题讨论】:

    标签: r ggplot2 patchwork


    【解决方案1】:

    关于宽度问题,您所做的嵌套——例如(p1 + p1)——会导致嵌套对象的响应不同。相反,您可以使用 plot_layout() 中的 design 参数来实现相同的效果,但会响应宽度。

    library(ggplot2)
    library(patchwork)
    
    p1 <- ggplot(mtcars) + 
      geom_point(aes(disp, wt, colour = mpg)) + 
      ggtitle('Plot 1')
    
    p2 <- ggplot(mtcars) + 
      geom_point(aes(carb, wt)) + 
      ggtitle('Plot 2')
    
    
    p3 <- ggplot(mtcars) + 
      geom_point(aes(hp, wt, colour = mpg)) + 
      ggtitle('Plot 3')
    
    p4 <- ggplot(mtcars) + 
      geom_area(aes(gear, carb)) + 
      ggtitle('Plot 4')
    
    
    # Patchwork graph with shared y-axis
    y_axis <- ggplot(data.frame(l = p1$labels$y, x = 1, y = 1)) +
      geom_text(aes(x, y, label = l), angle = 90) + 
      theme_void() +
      coord_cartesian(clip = "off")
    
    p1$labels$y <- p2$labels$y <- " "
    
    y_axis + p1 + p2 + p3 + p4 +
      plot_layout(widths = c(1, 15, 5),
                  guides = "collect",
                  design = "
                  123
                  145
                  ")
    

    reprex package (v0.3.0) 于 2020 年 12 月 16 日创建

    请注意,您正在删除 p2 的 y 轴标签,而我认为您的意思是从 p3 中删除它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2021-11-07
      • 2021-06-15
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2021-04-10
      相关资源
      最近更新 更多