有没有办法只在情节中显示图例?我尝试了解决方案here但没有成功:
library(gridExtra)
library(grid)
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)}
coverage_plot <- ggplot(data=m, aes(x=Time, y=Coverage, group=Technique, color=Technique)) +
geom_line(size=1) +
scale_colour_discrete(name="Technique") +
geom_point(aes(shape=Technique, colour = Technique), show.legend = T, size=3) +
scale_x_discrete(labels = seq(1, 30.0, by=1)) +
theme(legend.position="right", axis.text.x = element_text(angle = 90),text = element_text(size=14),legend.title=element_blank())+
labs(x = "Time (minutes)")+
scale_shape_discrete() +
guides(shape=guide_legend(override.aes=list(size=3, linetype=0)))
mylegend<-g_legend(coverage_plot)
p3 <- grid.draw(mylegend)
这里的p3
返回null!
有什么建议请留言
最佳答案
我希望我能发表评论..
不管怎样,我用diamonds
数据集形式ggplot2
尝试了你的代码,它工作得很好。您认为可以共享您的数据吗?
library(ggplot2)
library(gridExtra)
library(grid)
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)}
coverage_plot <- ggplot(data=diamonds, aes(x=carat, y=price, group=clarity, color=clarity)) +
geom_line(size=1) +
scale_colour_discrete(name="clarity") +
geom_point(aes(colour = clarity), show.legend = T, size=3) +
scale_x_discrete(labels = seq(1, 30.0, by=1)) +
theme(legend.position="right", axis.text.x = element_text(angle = 90),text = element_text(size=14),legend.title=element_blank())+
labs(x = "Time (minutes)")+
scale_shape_discrete() +
guides(shape=guide_legend(override.aes=list(size=3, linetype=0)))
mylegend<-g_legend(coverage_plot)
p3 <- grid.draw(mylegend)
我从 geom_point
中删除了 shape
,因为那里只有 6 个形状符号,而 diamonds
有 8 个变量。但除此之外都是一样的。
关于r - ggplot2图例仅在图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43366616/