下面是一个使用内置diamonds
数据帧的例子:
library(ggplot2)
library(gridExtra)
library(dplyr)
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
首先,我们将创建两个地块一同铺陈:
df <- count(diamonds, cut)
p1 = ggplot(df, aes(x=cut, y=n, label=format(n, big.mark=","), fill=cut)) +
geom_bar(stat="identity") +
geom_text(aes(y=0.5*n), colour="white") +
coord_flip() +
theme(legend.position="bottom")
p2 = ggplot(diamonds %>% sample_n(1000), aes(x=carat, y=price, colour=cut)) +
geom_point()
现在从p1
保存传说为单独的grob:
leg = g_legend(p1)
将两个图并排放置u唱歌arrangeGrob
,然后使用marrangeGrob
布置双小区布局和它下面的图例。请注意,我们也从原始图中删除了图例。
marrangeGrob(grobs=list(
arrangeGrob(grobs=lapply(list(p1,p2), function(p) {
p + guides(colour=FALSE, fill=FALSE)
}), ncol=2),
leg), ncol=1, nrow=2, heights=c(20,1))
好了,我们需要看到你正在运行的代码,最好用,让我们重新创建的情节和传说中的样本数据,看什么地方出了错。例如,如果你有两个图,'p1'和'p2',并且你在一个名为'leg'的对象中存在这个图例,那么例如'marrangeGrob(p1,p2,leg,widths = c(5,5 ,1))'应该工作。 – eipi10
嗯,它更像是我有一个名为leg和plot1 <-marrangeGrob(list_of_plots,ncol = 4,nrow = 5)的grob。我想把这个图例添加到我从这个 –
产生的pdf中。'g_legend'函数返回图例的grob。您需要在拨打'marrangeGrob'时加入这个grob。如果您提供可重复的示例,我可以提供代码。 – eipi10