我有一个ggplot对象:
ggplot(plot1,aes(x = c, y = value, colour = variable, linetype = variable,size = variable)) +
geom_line() +
scale_x_continuous(breaks=seq(1,10,1)) +
#scale_y_continuous(breaks=seq(0,1, 0.1))+
scale_colour_manual(values=c("blue3","red3")) +
scale_linetype_manual(values = c(3,1)) +
scale_size_manual(values = c(0.6,0.3)) +
xlab("b") +
ylab("a") +
theme_bw() +
theme(axis.text=element_text(size=5),
axis.title=element_text(size=5),
axis.line = element_line(size=0.25),
axis.ticks=element_line(size=0.25),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
legend.position="right" ,
legend.direction="vertical",
legend.title=element_blank(),
legend.text=element_text(size=8),
legend.background=element_blank(),
legend.key=element_blank())
我想分别绘制相应的图例。
是否有可能以某种方式提取它?
我尝试使用此功能将图例保存为grob,但它只返回并清空石英窗口,但没有图例。
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)}
来源:https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs
答案 0 :(得分:4)
使用简化版的情节代码:
# base plot
p1 <- ggplot(plot1,aes(x=c, y=value, colour=variable, linetype=variable, size=variable)) +
geom_line()
# extract the different legends
leg1 <- p1 + guides(linetype=FALSE, size=FALSE)
leg2 <- p1 + guides(colour=FALSE, size=FALSE)
leg3 <- p1 + guides(colour=FALSE, linetype=FALSE)
legend.colour <- gtable_filter(ggplot_gtable(ggplot_build(leg1)), "guide-box")
legend.linetype <- gtable_filter(ggplot_gtable(ggplot_build(leg2)), "guide-box")
legend.size <- gtable_filter(ggplot_gtable(ggplot_build(leg3)), "guide-box")
leg1Grob <- grobTree(legend.colour)
leg2Grob <- grobTree(legend.linetype)
leg3Grob <- grobTree(legend.size)
p2 <- p1 + guides(colour=FALSE, linetype=FALSE, size=FALSE)
# final plot were you can place the legends were you want them
finplot <- p2 +
annotation_custom(grob = leg1Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
annotation_custom(grob = leg2Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??) +
annotation_custom(grob = leg3Grob, xmin = ??, xmax = ??, ymin = ??, ymax = ??)
将??
替换为你想要放置图例的情节中的坐标。
如果您想单独绘制图例,请使用geom_blank