在ggplot中删除图例层

9

又是一个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)

如果您运行上述代码,将会得到一个图例,其中包含每个组的信息,但也会有一个表示均值的垂直线(geom_vline())的图例。我的问题是如何去掉这个垂直线的图例?


1
你已经将 cond 映射到了填充和颜色上。移除其中一个映射即可解决问题。 - Andrie
我的回答对你有用吗? - Paul Hiemstra
1个回答

18

根据您使用的ggplot2版本,您可能会遇到此问题。在R2.14.1上使用ggplot2 vs 0.9.0,我得到了这个图表:

enter image description here

该图表不包括垂直线的图例。在这个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)

enter image description here

这段代码能够复现你的问题。默认下,show_guide = FALSE。在旧版本中,你可以在 geom_vline 中添加 legend = FALSE 来省略图例。在当前版本中,添加 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ж Үеҝ—пјҢиҝҷжӯЈжҳҜжҲ‘жғіиҰҒзҡ„гҖӮе№ІжқҜгҖӮ - Hassantm
4
从ggplot 2.0.0版本开始,“show_guide”已被弃用。请改用“show.legend”。 - Lucas Fortini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接