ggplot2传奇只在一个情节中

时间:2017-04-12 10:12:51

标签: r plot

有没有办法只在情节中显示传奇?我尝试了解决方案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!

请提出任何建议

1 个答案:

答案 0 :(得分:1)

我希望我能发表评论.. 无论如何,我使用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)

我从shape移除了geom_point,因为那里只有6个形状符号而diamonds有8个变量。但除此之外,它是一样的。