2017-04-23 86 views
0

我使用方面視圖繪製了3個直方圖,並添加了平均值和中位數的虛線。如何將圖例添加到facet直方圖中的geom_vline?

enter image description here

我想補充一個傳說來指示V線是指統計。

ggplot(x, aes(x=earnw)) + geom_histogram(binwidth=100, colour="black", fill="white") + 
facet_grid(tuyear ~ .) + 
geom_vline(data=a, aes(xintercept=earnw.mean), linetype="dashed", size=1, color="mean") + 
geom_vline(data=b, aes(xintercept=earnw.med), linetype="dashed", size=1, color="median") + 
scale_color_manual(name = "statistics", values = c("mean" <- "red", "median" <- "blue")) + 
labs(title="Histogram for Weekly Earnings of Respondents") + 
labs(x="Weekly Earnings of Respondents", y="Count") + 
scale_x_continuous(breaks=seq(0,3000,200),lim=c(0,3000)) 

的folllowing代碼返回錯誤:

Error in grDevices::col2rgb(colour, TRUE) : invalid colour name 'mean'

+0

'scale_color_manual'需要的顏色作爲輸入到'值='使用標籤的描述屬性 – timfaber

回答

2

有幾種方法可以做到這一點。我將總結數據集,然後將此摘要發送到geom_vline。這裏使用虹膜數據集

iris.summary <- iris %>% 
    group_by(Species) %>% 
    summarise(mean.SL = mean(Sepal.Length), med.SL = median(Sepal.Length)) %>% 
    gather(key = stat, value = value, -Species) 

ggplot(iris, aes(x = Sepal.Length)) + 
    geom_histogram() + 
    facet_wrap(~ Species) + 
    geom_vline(data = iris.summary, aes(xintercept = value, colour = stat), linetype = "dashed")