2015-02-11 109 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