2015-02-11 77 views
1

我想用不同顏色的垂直線創建一個ggplot圖。這裏有一種方法來實現這個目標。ggplot2:彩色垂直線

mtcars$colors = rep(1:4, nrow(mtcars)/4) 

ggplot(mtcars, aes(x=wt, y=mpg)) + 
    geom_point() + 
    geom_vline(xintercept=subset(mtcars, colors==1)$wt, color="red") + 
    geom_vline(xintercept=subset(mtcars, colors==2)$wt, color="blue") + 
    geom_vline(xintercept=subset(mtcars, colors==3)$wt, color="yellow") + 
    geom_vline(xintercept=subset(mtcars, colors==4)$wt, color="green") 

enter image description here

這種解決方案也不是很方便的,當變量colors需要50個不同的值1),因爲它要求用戶寫入一個很長的表達(或以迭代地構造ggplot對象)和2- ),因爲它不會產生顏色的圖例。有更好的解決方案嗎?

回答

2

也許這反而:

+ geom_vline(aes(xintercept = wt,color = factor(colors))) + 
    scale_color_manual(values = c('red','blue','yellow','green')) 
+0

哦..這很簡單!謝謝喬蘭 – 2015-02-11 18:09:14