基于增加或减少的颜色ggplot线

时间:2017-09-25 17:09:03

标签: r ggplot2

我正在尝试根据线段的颜色是否大于它之前的点来更改线段的颜色。我在这里做错了什么?

示例:

from [1,4] to [2,5] would be green because the y value is increasing. 
from [1,4] to [2,1] would be red because the y value is decreasing.

我的代码:

set.seed(42)
df<-NULL
df$x<-rnorm(10,0,10)
df$y<-rnorm(10,0,10)
df$colors<-cbind(lapply(1:length(df$x),function(i){
  ifelse(df$x[i]>df$x[i-1],"#CC6666","#9999CC")
}))
df<-data.frame(df)


ggplot()+
  geom_line(aes(x=df$x,y=df$y),size=1.5,colour=df$color)+
  scale_color_manual(values=df$color)

1 个答案:

答案 0 :(得分:1)

这样的事情对你有用吗,我重新安排了你的示例数据,但我们可以使用geom_segment()dplyr::lead()来正确匹配颜色,并使用一点ggplot hack来制作标签再好一点,抛弃了NA:

set.seed(42)
df <- data.frame( x = rnorm(10,0,10),
                  y = rnorm(10,0,10) )

# base R
df <- df[order(df$x),]
df$color <- sapply(1:nrow(df), function(i) df$y[i] > df$y[i+1])
df$group <- "1"

library(tidyverse)
df <- arrange(df, x) %>% 
    mutate(color = y > lead(y),
           group = "1") # group everything togther or else we get two lines

ggplot()+
    geom_path(data = df,
              aes(x=x, y=y, color = color, group = group),size=1.5) +
    scale_color_manual(values = c("#CC6666","#9999CC"), na.value = "white",
                       labels = c("increase", "decrease", ""))

enter image description here