2017-01-09 88 views
-1

我有以下barplot其從the data-set 'temp'產生(數據位於此堆棧溢出頁面的底部,也可通過上述的此鏈接找到)。GGPLOT2:添加圖例和相關聯的圖例標題barplot

enter image description here

問題

目標是一個圖例添加到barplot(以上)標題爲冠層型用標籤表示樹冠下打開的右手側冠層

我試着用scale_colour_manual在另一計算器給出的答案,但我不能讓一個傳奇展現出來。

如果有人可以幫助,那麼許多在此先感謝

生成barplot是代碼:

假設你想繪製Canopy_Index每個Under_Open的手段,地形單元格,可以形成首先意味着:

df.means <- aggregate(Canopy_Index ~ Under_Open + Topography, df.melt, mean) 

然後,情節df.means使用的代碼從你的問題:

ggplot(df.means, aes(x = Topography, y = Canopy_Index, 
        fill = factor(Under_Open), group = Under_Open)) + 
    geom_bar(stat = "identity", position = "dodge") + 
    scale_fill_discrete(name = "Topographical Feature", 
         breaks = c("Under_tree", "Open_Canopy"), 
         labels = c("Under Canopy", "Open Canopy")) + 
    xlab("Topographical Feature") + ylab("Canopy Index") + 
    scale_colour_manual("Canopy Type", values = c("red", "blue")) + 
    theme(axis.text.x = element_text(angle = 45, hjust = 1), 
     text = element_text(size=14)) + 
    theme(panel.background = element_blank(), 
     panel.grid.major = element_blank(), 
     panel.grid.minor = element_blank(), 
     panel.border = element_blank()) + 
    theme(axis.line.x =  element_line(color="black", size = 0.8), 
     axis.line.y = element_line(color="black", size = 0.8)) 
+0

在我的機器上運行該代碼有傳說顯示na MED的「地貌形態」 – bouncyball

+1

使用你的代碼我得到一個傳奇,它是由scale_fill_discrete生產。由於aes中沒有顏色參數,因此scale_colour_manual不能生成圖例。 – Haboryme

+0

很奇怪!運行代碼後,圖例無法顯示。你有什麼建議嗎? –

回答

0

非常感謝「泰勒斯提供的代碼來解決此問題

代碼相關聯的圖例產生barplot:

 ggplot(df.means, aes(x=Topography, y=Canopy_Index,fill=Under_Open)) + 
    geom_bar(stat="identity", position="dodge") + 
    scale_fill_discrete(name="Canopy Type", 
       breaks=c("Under_tree", "Open_Canopy"), 
       labels=c("Under Canopy", "Open Canopy")) + 
    xlab("Topographical Feature") + ylab("Canopy Index") 

Barplot

enter image description here