2016-07-26 69 views
3

實例數據幀(如果有做這更好/更地道的方式,讓我知道):有一組點線圖的獨立傳說,和垂直線圖

n <- 10 
group <- rep(c("A","B","C"),each = n) 
x <- rep(seq(0,1,length = n),3) 
y <- ifelse(group == "A",1+x,ifelse(group == "B",2+2*x,3+3*x)) 
df <- data.frame(group,x,y) 
xd <- 0.5 
des <- data.frame(xd) 

我想爲df中的數據創建點線圖,在xd指示的x位置添加垂直曲線,並獲得兩者的可讀圖例。我試過如下:

p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group)) 
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue") 
p 

enter image description here 不太什麼,我腦子裏想的,還有的垂直線沒有傳說。

一個小的修改(我不明白爲什麼geom_vline是一個show.legend參數,而且默認FALSE爲數不多的幾何形狀的一個!):

p <- ggplot(data = df, aes(x = x, y = y, color = group)) + geom_point() + geom_line(aes(linetype=group)) 
p <- p + geom_vline(data = des, aes(xintercept = xd), color = "blue", show.legend = TRUE) 
p 

enter image description here

至少現在的垂直條顯示在圖例中,但我不希望它與group處於相同的「類別」(?)。我想要另一個圖例條目,標題爲Design,並且只包含垂直線。我怎樣才能做到這一點?

回答

4

一種可能的方法是添加一個額外的虛擬美學像fill =,我們將在隨後使用它來創建組合的第二個傳說與scale_fill_manual()

ggplot(data = df, aes(x = x, y = y, color = group)) + 
     geom_point() + 
     geom_line(aes(linetype=group), show.legend = TRUE) + 
     geom_vline(data = des, 
        aes(xintercept = xd, fill = "Vertical Line"), # add dummy fill 
        colour = "blue") + 
     scale_fill_manual(values = 1, "Design", # customize second legend 
       guide = guide_legend(override.aes = list(colour = c("blue")))) 

enter image description here

+1

我會給你+2對於**夢幻般的**瑞克頭像,但唉,我只能給你+1這個不錯的答案:) – DeltaIV

+0

我需要在'scale_fill_manual'中設置'override.aes',但爲什麼你必須移動' geom_line幾何中的show.legend = TRUE?這是正確的,否則解決方案不起作用,但我不明白爲什麼。 – DeltaIV

+0

你也可以把它放在'geom_vline()'裏面,但是這會混淆傳說由於某種原因顯示的方式。這似乎是一個已知的,但尚未完全解決的問題,請看這裏:https://github.com/hadley/ggplot2/issues/1267 – mtoto