R ggplot2仅在绘图中显示图例

R ggplot2仅在绘图中显示图例,r,plot,R,Plot,有没有办法只在情节中显示图例?我尝试了解决方案,但没有成功: 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]]

有没有办法只在情节中显示图例?我尝试了解决方案,但没有成功:

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)
库(gridExtra)
图书馆(网格)
g_legend我希望我能发表评论。。
不管怎样,我用
diamonds
dataset表单
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)
库(ggplot2)
图书馆(gridExtra)
图书馆(网格)
g_传说