R中一个Cowplot网格的共享图例 [英] One shared legend for a cowplot grid in R

查看:629
本文介绍了R中一个Cowplot网格的共享图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用包cowplot构建了一个网格(用于标记A-D中的图).使用包ggplot2:

I just built a grid with package cowplot (to label the plots from A-D). The plots are made with package ggplot2:

pfour<-ggplot(four, aes(x=Concentration, y=Percentage, fill=Phenotype)) + 
 geom_bar(stat='identity',color='black') +
 scale_fill_grey(start = .4, end = .9) + 
 theme_bw()+ylab("Distribution") + 
 xlab("Contentration [mg/ml]") + 
 ggtitle("96 hpf") +
 theme(legend.title = element_text(colour="black", size=10, face="bold")) +
 theme(legend.background = element_rect(fill="white",
                                        size=0.5, linetype="solid", 
                                        colour ="black")) +
 scale_x_discrete(limits=c('uninjected','control','0.002', '0.02', '0.2'),
                  labels=c('uninjected\n(n=251)',
                           'control\n(n=248)', 
                           '0.002\n(n=205)', 
                           '0.02\n(n=222)', 
                           '0.2\n(n=203)'))

数据看起来像这样(4个不同的表,它们的百分比略有不同,但原理相同):

the data looks like that (4 different tables with slightly different percentages but the same principle):

Concentration,Percentage,Phenotype
uninjected,0.996015936,0
uninjected,0,1
uninjected,0.003984064,2
uninjected,0,3
uninjected,0,4
control,0.995967742,0
control,0.004032258,1
control,0,2
control,0,3
control,0,4
0.002,0.985365854,0
0.002,0.004878049,1
0.002,0.004878049,2
0.002,0,3
0.002,0.004878049,4
0.02,0.981981982,0
0.02,0.004504505,1
0.02,0.004504505,2
0.02,0.004504505,3
0.02,0.004504505,4
0.2,0.985221675,0
0.2,0.004926108,1
0.2,0,2

看起来像这样:

该代码是:

plot_grid(ponezoom, ptwozoom,pthreezoom,pfourzoom, align='h', labels=c('A', 'B','C','D'))

现在,我想知道是否有可能为所有四个地块共享一个图例,因为它会占用大量地块空间来进行4次绘制.感谢您的帮助.

Now I was wondering if it is possible to get one single shared legend for all four plots as it steals a lot of plotspace to have it 4 times. I appreciate any help.

推荐答案

方法是使用隐藏的图例theme(legend.position="none")构建图. 然后从其中一个对象中提取图例grob.

The approach is to build your plots with the legend hidden theme(legend.position="none"). Then extract the legend grob from one of those objects.

grobs <- ggplotGrob(pfour)$grobs
legend <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]

然后将图例绘制为单独的图". 要使图例在右侧,您可以执行以下操作:

Then plot the legend as a seperate 'plot'. To have the legend at to the right you might do:

# build grid without legends
pgrid <- plot_grid(pone, ptwo, pthree, pfour, ncol = 2)
# add legend
p <- plot_grid(pgrid, legend, ncol = 2, rel_widths = c(1, .1))

这篇关于R中一个Cowplot网格的共享图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆