首页 > 解决方案 > 使用 cowplot 和 ggplot2 在某些行周围绘制边框

问题描述

我想以某种方式表明多面板图中的某些行应该一起比较。例如,我想制作这个情节:

在此处输入图像描述

看起来像这个图(用 PowerPoint 制作的面板周围有方框):

在此处输入图像描述

这是我使用第一个图制作的代码。我使用了ggplot和cowplot:

require(cowplot)
theme_set(theme_cowplot(font_size=12)) # reduce default font size
plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5)
plot.diamonds <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))
plot.mpg2 <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + 
  geom_point(size=2.5)
plot.diamonds2 <- ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() +
  theme(axis.text.x = element_text(angle=70, vjust=0.5))
plot_grid(plot.mpg, plot.diamonds,plot.mpg2, plot.diamonds2, nrow=2,labels = c('A', 'B','C','D'))

我可以对此代码进行更改以获得我想要的边框吗?或者我什至可以让面板 A 和 B 的颜色与面板 C 和 D 的背景颜色略有不同?那可能会更好。

标签: rggplot2cowplot

解决方案


由于 的结果plot_grid()是一个 ggplot 对象,因此一种方法是使用嵌套的绘图网格:plot_grid()每行一个,并通过添加适当的边框theme()

plot_grid(
  # row 1
  plot_grid(plot.mpg, plot.diamonds, nrow = 1, labels = c('A', 'B')) +
    theme(plot.background = element_rect(color = "black")),

  # row 2
  plot_grid(plot.mpg2, plot.diamonds2, nrow = 1, labels = c('C', 'D')) +
    theme(plot.background = element_rect(color = "black")), 

  nrow = 2)

阴谋


推荐阅读