2013-10-03 96 views
0

我正在使用ggplot2繪製一些具有傳說的密度圖,但我無法將圖例添加到最終結果中。無法爲ggplot2中的多個密度圖創作圖例

m <- ggplot(chickwts, aes(x = weight)) 
m + geom_density(kernel = "gaussian", adjust = .3, colour="green", size=1)+ 
    geom_density(kernel = "gaussian", adjust = 1, colour="red", size=1)+ 
    geom_density(kernel = "gaussian",adjust = 5, colour="blue", size=1)+ 
    geom_density(kernel = "gaussian",adjust = 10, colour="yellow", size=1)+ 
    geom_density(kernel = "gaussian",adjust = 20, colour="orange", size=1) 

我已經使用了幾個我在這裏找到的語法,但沒有一個不起作用。 謝謝。

回答

1

ggplot2將其傳說美學,或論據傳遞到aes()函數。通常,您會指定一個因子作爲顏色美學,這會自動創建顏色圖例。但是,chickwts數據集中沒有內置密度分組因子,因此您必須製作自己的比例和標籤。

,而不是直接在geom_density()定義顏色,你可以定義對應於您在scale_colour_manual()創建,像這樣一個自定義的色標指定的顏色美學:

m <- ggplot(chickwts, aes(x = weight)) 
m + geom_density(kernel = "gaussian", adjust = .3, aes(colour=".3"), size=1)+ 
    geom_density(kernel = "gaussian", adjust = 1, aes(colour="1"), size=1)+ 
    geom_density(kernel = "gaussian",adjust = 5, aes(colour="5"), size=1)+ 
    geom_density(kernel = "gaussian",adjust = 10, aes(colour="10"), size=1)+ 
    geom_density(kernel = "gaussian",adjust = 20, aes(colour="20"), size=1) + 
    scale_colour_manual(values=c(".3"="green", "1"="red", "5"="blue", "10"="yellow", "20"="orange"), name="Densities") 

Density plot example

+0

太謝謝你了。 – user2843490