2013-08-05 137 views
22

我在ggplot中有一個繪圖,其中有4個單獨的行,我已經添加了一個單獨的geom_line()參數。我想添加圖例,但scale_colour_manual在這種情況下不起作用。當我單獨添加變量時,添加圖例的正確方法是什麼?當手動添加行時,將圖例添加到ggplot

這裏是我的代碼:

ggplot(proba[108:140,], aes(c,four)) + 
    geom_line(linetype=1, size=0.3) + 
    scale_x_continuous(breaks=seq(110,140,5)) + 
    theme_bw() + 
    theme(axis.line = element_line(colour = "black", size=0.25), 
      panel.grid.major = element_blank(), 
      panel.grid.minor = element_blank(), 
      panel.border = element_blank(), 
      panel.background = element_blank()) + 
    theme(axis.text.x = element_text(angle = 0, hjust = +0.5, size=6,color="black")) + 
    theme(axis.text.y = element_text(angle = 0, hjust = -100, size=6, color="black")) + 
    theme(axis.ticks=element_line(colour="black",size=0.25)) + 
    xlab("\nTime-steps") + 
    ylab("Proportion correct\n") + 
    theme(axis.text=element_text(size=8),axis.title=element_text(size=8)) + 
    geom_line(aes(c,three), size=0.2, linetype=2) + 
    geom_line(aes(c,one),linetype=3, size=0.8, colour="darkgrey") + 
    geom_line(aes(c,two), linetype=1, size=0.8, colour="darkgrey") 
+0

你能發佈你的代碼嗎?在調用'aes'時設置'color =「Line Name」'應該可以。 – Peyton

+0

我已經有了一個參數的顏色,但它不會將其顯示爲圖例。我發佈了我的代碼。 – user1723765

+3

將'color'參數放在'aes'中,而不是將其設置爲顏色名稱,將其設置爲您想要在圖例中出現的名稱。然後使用'scale_color_manual'將該名稱映射到所需的顏色。 – Peyton

回答

21

aes只需設置顏色名稱到任何線的上傳奇的名字應該是。

我沒有數據,但這裏的使用iris隨機y值線爲例:

library(ggplot2) 

line.data <- data.frame(x=seq(0, 10, length.out=10), y=runif(10, 0, 10)) 

qplot(Sepal.Length, Petal.Length, color=Species, data=iris) + 
    geom_line(aes(x, y, color="My Line"), data=line.data) 

enter image description here

要注意的關鍵問題是,你正在創建一個審美映射,但不是將顏色映射到數據框中的列,而是將其映射到您指定的字符串。 ggplot將爲該值分配顏色,就像來自數據框的值一樣。你可以通過添加Species列的數據幀都產生同樣的情節如上:

line.data$Species <- "My Line" 
qplot(Sepal.Length, Petal.Length, color=Species, data=iris) + 
    geom_line(aes(x, y), data=line.data) 

無論哪種方式,如果你不喜歡的顏色ggplot2受讓人,那麼你可以使用scale_color_manual指定自己:

qplot(Sepal.Length, Petal.Length, color=Species, data=iris) + 
    geom_line(aes(x, y, color="My Line"), data=line.data) + 
    scale_color_manual(values=c("setosa"="blue4", "versicolor"="red4", 
           "virginica"="purple4", "My Line"="gray")) 

enter image description here

另一種選擇是隻是直接標記線,或使從上下文明顯的線的目的。真的,最好的選擇取決於你的具體情況。

+2

這適用於上述代碼中第一個aes()參數中的第一個變量,但對於其他geom_line()s – user1723765

+0

這是不是適合你嗎?你可以發佈你的代碼和數據兩者 - 基本上可以運行以查看您的位置的示例? – Peyton