0

我正在尝试通过拼凑组合几个 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")


4

1 回答 1

1

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

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 包于 2020-12-16 创建(v0.3.0)

小注意,您正在删除 的 y 轴标签p2,而我认为您的意思是从p3.

于 2020-12-16T09:41:54.480 回答