我有一个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())我想单独绘制相应的图例。
有没有可能以某种方式提取出来?
我尝试使用此函数来保存一个图例一个格罗布,但它只返回和空的石英窗口,但没有图例。
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
发布于 2014-02-25 02:48:12
使用简化版本的绘图代码:
# 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创建一个空白图
https://stackoverflow.com/questions/21989182
复制相似问题