ggplot2:彩色垂直线
ggplot2: coloured vertical lines
我想用不同颜色的垂直线创建一个 ggplot 图。这是实现此目标的一种方法。
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) 因为它不会为颜色生成图例。有更好的解决方案吗?
也许是这样:
+ geom_vline(aes(xintercept = wt,color = factor(colors))) +
scale_color_manual(values = c('red','blue','yellow','green'))
我想用不同颜色的垂直线创建一个 ggplot 图。这是实现此目标的一种方法。
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) 因为它不会为颜色生成图例。有更好的解决方案吗?
也许是这样:
+ geom_vline(aes(xintercept = wt,color = factor(colors))) +
scale_color_manual(values = c('red','blue','yellow','green'))