2016-06-21 56 views
0

我想要生成一個用ggplot2製作的複合圖表的好傳說,其中有一個閃避的barplot和一個用於顯示鋇的參考值的水平線泥。問題是,hline圖例的特徵是「污染」也是barplot的特徵。我已經看到類似的主題試圖調整提出的其他解決方案,但沒有任何顯着的結果。ggplot2創建一個geom_hline圖例而不浪費barplot一個

這裏我舉的例子:

數據框:

 Position Year Value 
     Position 1 1999 12 
     Position 2 1999 14 
     Position 3 1999 15 
     Position 1 2000 13 
     Position 2 2000 11 
     Position 3 2000 21 
     Position 1 2001 12 
     Position 2 2001 13 
     Position 3 2001 16 

代碼:

ggplot(input, aes(fill=Year , x=Position, y=Value)) + 

    geom_bar(stat="identity", 
    position="dodge", size=0.1, width=0.5, show.legend=TRUE) + 
    labs(title="Barium concentration in the soil") + 
    xlab("Samples") + 
    ylab("Concentration in ng/kg") + 
    scale_y_continuous(limits = c(0, 30)) + 
    #color of barplot 
    scale_fill_manual(values=c("grey40", "grey70", "grey80")) + 

    #limit value 
    geom_hline(aes(yintercept=40, colour = "red"), size=0.9, alpha=0.8, show.legend=TRUE) 

這是圖表

chart obtained

正如你可以看到hline傳說的功能正在浪費barplot之一。

+0

您需要的AES移出'顏色=「red''從你的' geom_hline'。 – Heroka

+0

通過在'aes'之外移動'color ='red'''命令,你只需從圖表中刪除hline圖例。相反,我想保留它:'geom_hline'圖例沒問題。問題在於barplot傳說被污染了酒吧裏的黑色線條bols,這個問題與創建'geom_hline'傳說有關。 – Thaunes

+0

[從顏色和填充圖例中刪除線條可能的重複](http://stackoverflow.com/questions/29941900/remove-lines-from-color-and-fill-legends) – aosmith

回答

3

你可能會做這種方式:

ggplot(input, aes(fill=Year , x=Position, y=Value)) + 
    geom_bar(stat="identity", position="dodge", size=0.1, width=0.5) + 
    labs(title="Barium concentration in the soil") + xlab("Samples") + 
    ylab("Concentration in ng/kg") + 
    scale_y_continuous(limits = c(0, 30))+ 
    geom_hline(aes(yintercept=20, colour="limit"), size=0.9, alpha=0.8) + 
    scale_fill_manual(values=c("grey40", "grey70", "grey80")) + 
    scale_color_manual(name="Foo", values=c(limit="red")) + 
    theme(legend.key = element_rect(fill = "white", colour = "white")) 

然後情節是這樣的:

enter image description here

+0

謝謝!完美清晰的解決方案!有沒有可能改變傳說中紅線後面的灰色背景? – Thaunes

+0

不客氣。我編輯了我的awnser。該代碼現在更具慣用性,圖例最後一個條目中的矩形背景現在變成了白色。 –

相關問題