2016-04-28 124 views
1

我想添加圖例的圖例,但它不起作用。 你有什麼想法嗎?如何使用ggplot將圖例添加到多個直方圖?

這裏是我的代碼:

ggplot(data =stats_201507_AF) + 
    geom_histogram(aes(gross_ind),fill="dodgerblue3", show.legend =T,bins=25)+ 
    geom_histogram(aes(net_ind),fill="springgreen4",show.legend = T,bins=25) + 
    geom_histogram(aes(tax_ind),fill="gold2",show.legend = T, bins=25) + 
    xlab("Indices")+ 
    scale_colour_manual(values=c("dodgerblue3","springgreen4","gold2")) 

我想用一個相應顏色的每個直方圖的描述。

感謝很多提前

+0

您使用ggplot的方式是將數據以正確的格式繪製出來,這可能還沒有完成。您可能需要將數據從廣泛轉換爲長數據,但如果沒有可用於演示數據的可重複示例,關於如何做到這一點的詳細信息將無法解釋。 – joran

+0

要添加圖例,您需要確定填充位於'aes()'映射內的變量。要做到這一點,您必須重新構建數據框架。 –

+0

[將圖例添加到ggplot2線圖]可能重複(http://stackoverflow.com/questions/10349206/add-legend-to-ggplot2-line-plot) – aosmith

回答

1

如果你不想重塑你的數據,只是這樣做:

ggplot(iris) + 
    geom_histogram(aes(x = Sepal.Length, fill = "Sepal.Length"), 
       position = "identity", alpha = 0.5) + 
    geom_histogram(aes(x = Sepal.Width, fill = "Sepal.Width"), 
       position = "identity", alpha = 0.5) + 
    scale_fill_manual(values = c(Sepal.Length = "blue", 
           Sepal.Width = "red")) 

的關鍵是,你需要一些映射到fillaes。當然,將數據轉換爲長格式(實際上有一列作爲結果映射到fill)通常是可取的。