2012-03-26 82 views
9

另一個ggplot圖例問題!刪除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()的傳說?

+1

您已將'cond'映射爲填充以及顏色。刪除其中一個映射應該可以解決問題。 – Andrie 2012-03-26 14:12:32

+0

我的答案是否對你有用? – 2012-03-27 13:34:47

回答

15

根據您使用的ggplot2版本,您會遇到此問題。使用GGPLOT2 VS上R2.14.1 0.9.0我得到這個圖:

enter image description here

不包括在V線的傳說。在這個版本的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。在舊版本中,您可以將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

+0

謝謝@保羅...升級ggplot啓用了'show_guide'標誌,它做我想做的。乾杯。 – Hassantm 2012-03-29 10:45:33

+1

從ggplot 2.0.0開始:'show_guide'已被棄用。請改用'show.legend'。 – 2015-12-22 17:46:48