ggplot2:彩色垂直线 [英] ggplot2: coloured vertical lines

查看:171
本文介绍了ggplot2:彩色垂直线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用不同颜色的垂直线创建一个ggplot图.这是实现此目标的一种方法.

I'd like to create a ggplot graph with vertical lines of different colors. Here one way to achieve this goal.

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")

当变量colors接受50个不同值时,此解决方案不是很方便:1)因为它要求用户编写一个很长的表达式(或迭代地构造ggplot对象)和2),因为它不产生图例颜色.有更好的解决方案吗?

This solution is not very handy when the variable colors takes 50 different values 1) because it asks the user to write a very long expression (or to construct the ggplot object iteratively) and 2) because it does not produce legends for the colors. Is there a better solution?

推荐答案

也许是这样:

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

这篇关于ggplot2:彩色垂直线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆