2017-02-06 31 views
1

我有一個散點圖,我想要4個指引線。我沒有直接使用數據集中的變量來定義劇本腳本中的那些行。 (垂直線是x值的平均值和中值,另外兩條線的斜率是1和0.5)。
如何定義線條的顏色並獲取正確的圖例標籤?在我的情節中,顏色和標籤混在一起。ggplot2:使用scale_colour_manual混合標籤和顏色

回答here (possibly duplicate)的問題與我上面的問題類似,但並不完全,我想。前面的問題是關於scale_colour - 和scale_fill_manual之間的區別,以及包含aes()來獲得傳奇的重要性,我想。我的問題是關於傳說標籤和顏色的混合,因爲我沒有在geom_- call中定義值並在scale_colour_manual()中分隔了值和顏色。

我的代碼:

library(dplyr) 
df <- iris %>% 
    group_by(Species) %>% 
    do({ 
    mod = lm(Sepal.Length~Petal.Length, data = .) 
    data.frame(Intercept = coef(mod)[1], 
       Slope = coef(mod)[2], 
       SD= summary(mod)$coefficients[2,2]) 
    }) 

meanSlope <- mean(df$Slope) 
medianSlope <- median(df$Slope) 

library(ggplot2) 
ggplot(data=df, aes(x=Slope, y=SD)) + 
    geom_point() + 
    scale_x_continuous(limits = c(0,1.0)) + 
    scale_y_continuous(limits = c(0,1.0))+ 
    geom_abline(aes(intercept = 0, slope = 1, colour="red"), show.legend = TRUE) + 
    geom_abline(aes(intercept = 0, slope = 0.5, colour="blue"), show.legend = TRUE) + 
    geom_vline(aes(xintercept = meanSlope, colour= "green"), show.legend = TRUE) + 
    geom_vline(aes(xintercept= medianSlope, colour= "darkgreen"), show.legend = TRUE) + 
    scale_colour_manual(name="Guide lines", values=c("red", "blue", "green", "darkgreen"), 
         labels=c("1 SD", "0.5 SD", "mean", "median")) 

enter image description here

+0

的可能重複的http:/ /stackoverflow.com/questions/24063163/how-to-add-manual-colors-for-ag gplot2-geom-smooth-geom-line – akrun

+0

[如何爲ggplot2添加手動顏色(geom \ _smooth/geom \ _line)](http://stackoverflow.com/questions/24063163/how-to-add -manual-顏色換一個-GGPLOT2-GEOM的光滑的geom線) – Axeman

回答

3

嘗試映射到該行的名稱,然後設置顏色算賬:

ggplot(data=df, aes(x=Slope, y=SD)) + 
    geom_point() + 
    scale_x_continuous(limits = c(0, 1.0)) + 
    scale_y_continuous(limits = c(0, 1.0))+ 
    geom_abline(aes(intercept = 0, slope = 1, colour = "1 SD"), show.legend = TRUE) + 
    geom_abline(aes(intercept = 0, slope = 0.5, colour = "0.5 SD"), show.legend = TRUE) + 
    geom_vline(aes(xintercept = meanSlope, colour = "mean"), show.legend = TRUE) + 
    geom_vline(aes(xintercept= medianSlope, colour = "median"), show.legend = TRUE) + 
    scale_colour_manual(name = "Guide lines", 
         values = c('1 SD' = "red", '0.5 SD' = "blue", 
           mean = "green", median = "darkgreen")) 

enter image description here