使用Cowplot和ggplot2在某些行周围绘制边框 [英] Draw border around certain rows using cowplot and ggplot2
问题描述
我想以某种方式指出多面板图形中的某些行应该一起比较.例如,我要绘制此图:
I want to somehow indicate that certain rows in a multipanel figure should be compared together. For example, I want to make this plot:
看起来像这样的情节(在用PowerPoint制作的面板周围带有框):
Look like this plot (with boxes around panels made with PowerPoint):
这是我使用第一个情节编写的代码.我用了ggplot和cowplot:
Here's the code I made to use the first plot. I used ggplot and 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的背景略有不同?可能会更好.
Is there a change I can make to this code to get the borders that I want? Or maybe can I even make the panels A and B have a slightly different color than the background for panels C and D? That might be even better.
推荐答案
由于plot_grid()
的结果是ggplot对象,因此,实现此目的的一种方法是使用嵌套的图网格:每行一个plot_grid()
,通过theme()
添加的适当边框.
Since the result of plot_grid()
is a ggplot object, one way to do this is to use nested plot grids: one plot_grid()
for each row, with the appropriate border added via 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)
这篇关于使用Cowplot和ggplot2在某些行周围绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!