R 生成带有共享图例的ggplot时删除背景
我正在尝试生成一个R 生成带有共享图例的ggplot时删除背景,r,ggplot2,legend,R,Ggplot2,Legend,我正在尝试生成一个ggplot,它共享ggplot列表中的图例 这是我的密码: #generate the list of plots: set.seed(1) plot.list <- vector(mode="list",2) plot.list[[1]] <- ggplot(data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30)),aes(val,color=group))+geom_density(adjust=1)+theme
ggplot
,它共享ggplot
列表中的图例
这是我的密码:
#generate the list of plots:
set.seed(1)
plot.list <- vector(mode="list",2)
plot.list[[1]] <- ggplot(data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30)),aes(val,color=group))+geom_density(adjust=1)+theme_minimal()
set.seed(10)
plot.list[[2]] <- ggplot(data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30)),aes(val,color=group))+geom_density(adjust=1)+theme_minimal()
以及
现在,制作一个分享他们传奇的情节:
g <- ggplotGrob(plot.list[[1]]+theme_minimal()+theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
plot(legend)
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plot.list,function(x) x+theme_minimal()+theme(legend.position="none"))
gl <- c(gl,nrow=1,ncol=2)
combined <- switch(position,"bottom"=arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=2,
widths=unit.c(unit(1,"npc")-lwidth,lwidth)))
g也许您最好组合数据帧并使用facet\u wrap()
set.seed(1)
df1plot()
不是正确的函数。试试网格。draw@dan这个答案有用吗?我无法复制你的代码。我得到错误:未找到对象“位置”
。
plot.list[[2]]
g <- ggplotGrob(plot.list[[1]]+theme_minimal()+theme(legend.position="right"))$grobs
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
plot(legend)
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
gl <- lapply(plot.list,function(x) x+theme_minimal()+theme(legend.position="none"))
gl <- c(gl,nrow=1,ncol=2)
combined <- switch(position,"bottom"=arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=1,
heights = unit.c(unit(1, "npc") - lheight, lheight)),
"right" = arrangeGrob(do.call(arrangeGrob,gl),
legend,
ncol=2,
widths=unit.c(unit(1,"npc")-lwidth,lwidth)))
set.seed(1)
df1<-data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30),dfz=1)
set.seed(10)
df2<-data.frame(group=rep(LETTERS[1:3],10),val=rnorm(30),dfz=2)
df<-rbind(df1,df2)#combine dataframes
ggplot(df,aes(val,color=group))+geom_density(adjust=1)+theme_minimal()+
facet_wrap(~dfz,scales='free') #facet_wrap by distinguishing column