r - ggplot2图例仅在图中

标签 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!

有什么建议请留言

最佳答案

我希望我能发表评论.. 不管怎样,我用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/

相关文章:

r - 需要有限的 'ylim' 值错误

python - 使用 matplotlib 中的数据框绘制 3D 图

python - 调查结果的条形图为 pd.value_counts()

python - 如何更改三元图的 Axis 刻度顺序?

r - 使用模型平均累积链接混合模型进行概率预测,该模型在 ordinal 包中安装了 clmm

r - ggplot2 中 geom_bar 图的边框颜色错误

r - 不要转义 Rmarkdown 文件中的特殊字符

R : Updating an entry in mongodb using mongolite

python - 将数据框列名称绘制为标签

matlab - bar3 颜色取决于 zdata