14

我刚刚用包构建了一个网格cowplot(以标记来自 AD 的图)。这些图是用 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 个不同的表格,百分比略有不同,但原理相同):

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 次。我很感激任何帮助。

4

2 回答 2

16

一个小插图显示了如何做到这一点。

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

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

然后将图例绘制为单独的“情节”。要将图例放在右侧,您可以这样做:

# 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))
于 2016-05-20T11:33:33.263 回答
3

您可以使用包中的ggarrange功能ggpubr。它有一个合乎逻辑的论据common.legend。你只需要设置它TRUE。在您的情况下,代码块将是:

library(ggpubr)

ggarrange(ponezoom, ptwozoom, pthreezoom, pfourzoom,
align='h', labels=c('A', 'B','C','D'),
common.legend = T)

请参阅数据集示例mtcars

library(tidyverse)
library(ggpubr)

# Create first plot
mtcars %>% 
  ggplot(aes(mpg, hp, color = factor(cyl))) +
  geom_point(size = 2) +
  theme_minimal()-> plot1

# Create second plot
mtcars %>% 
  ggplot(aes(disp, drat, color = factor(cyl))) +
  geom_point(size = 2) +
  theme_minimal() -> plot2

# Create grid
ggpubr::ggarrange(plot1, plot2, # list of plots
                  labels = "AUTO", # labels
                  common.legend = T, # COMMON LEGEND
                  legend = "bottom", # legend position
                  align = "hv", # Align them both, horizontal and vertical
                  nrow = 2)  # number of rows

瞧:

在此处输入图像描述

于 2020-02-13T09:19:46.773 回答