【问题标题】:removing a layer legend in ggplot删除 ggplot 中的图层图例
【发布时间】:2012-03-26 14:06:49
【问题描述】:

另一个 ggplot 传奇问题!

我有一个表单数据集

test <- data.frame(
  cond = factor(rep(c("A", "B"), each=200)), 
  value = c(rnorm(200), rnorm(200, mean=0.8))
)

所以两组和一些值,我想绘制密度。我还想在图中添加一条表示每个组平均值的线,所以我:

test.cdf <- ddply(test, .(cond), summarise, value.mean=mean(value))

然后在ggplot调用中:

ggplot(test, aes(value, fill=cond)) + 
  geom_density(alpha=0.5) + 
  labs(x='Energy', y='Density', fill='Group') + 
  opts(
    panel.background=theme_blank(), 
    panel.grid.major=theme_blank(), 
    panel.grid.minor=theme_blank(), 
    panel.border=theme_blank(), 
    axis.line=theme_segment()
  ) + 
  geom_vline(data=test.cdf, aes(xintercept=value.mean, colour=cond), 
    linetype='dashed', size=1)

如果你运行上面的代码,你会得到一个表示每个组的图例,还有一个表示平均值指标 vline 的图例。我的问题是如何摆脱geom_vline() 的传说?

【问题讨论】:

  • 您已将cond 映射到填充和颜色。删除其中一个映射应该可以解决问题。
  • 我的回答对你有用吗?

标签: r ggplot2 legend


【解决方案1】:

根据您使用的 ggplot2 版本,您会遇到此问题。在 R2.14.1 上使用 ggplot2 与 0.9.0 我得到这张图:

其中不包括 vline 的图例。在这个版本的 ggplot2 中,您可以使用 show_guide 调整图例的出现:

ggplot(test, aes(value, fill=cond)) + 
  geom_density(alpha=0.5) + 
  labs(x='Energy', y='Density', fill='Group') + 
  opts(
    panel.background=theme_blank(), 
    panel.grid.major=theme_blank(), 
    panel.grid.minor=theme_blank(), 
    panel.border=theme_blank(), 
    axis.line=theme_segment()
  ) + 
  geom_vline(data=test.cdf, aes(xintercept=value.mean, colour=cond), 
    linetype='dashed', size=1, show_guide = TRUE)

重现您的问题。默认为show_guide = FALSE。在旧版本中,您可以将legend = FALSE 添加到geom_vline 以省略图例。添加legend = FALSE 在当前版本中仍然有效,但会引发警告:

Warning message:
In get(x, envir = this, inherits = inh)(this, ...) :
  "legend" argument in geom_XXX and stat_XXX is deprecated. Use show_guide = TRUE or show_guide = FALSE for display or suppress the guide display.

我建议升级ggplot2

【讨论】:

  • 谢谢@Paul... 升级 ggplot 启用了 show_guide 标志,它可以满足我的需求。干杯。
  • 从 ggplot 2.0.0 开始:show_guide 已被弃用。请改用show.legend
猜你喜欢
  • 2018-11-03
  • 2016-06-07
  • 1970-01-01
  • 2016-04-09
  • 2021-12-07
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多