How to plot a line chart with different colors depending on the value?



  • Suppose the following data:

    set.seed(1)
    y<-rnorm(101)
    x<-seq(from=0, to=100,by=1)
    

    I want to make a plot with a line that has different color for negative values.

    To make a point chart, just the command below:

    plot(x,y,col=ifelse(y>0,"blue","red"))
    

    inserir a descrição da imagem aqui

    However, if I change to a line chart does not work.

    plot(x,y,col=ifelse(y>0,"blue","red"),type="l")
    

    inserir a descrição da imagem aqui

    If I try to do with it ggplot2 It's not working either. It attaches to the thread the color of the previous point.

    library(ggplot2)
    df<-data.frame(x,y)
    df$cat<-y>0
    ggplot(df,aes(x,y,color=cat)) + geom_path(aes(group=1))
    

    inserir a descrição da imagem aqui

    How to make for the R correctly assign the red color to negative values and blue color to positive values in the line plot?



  • A partial "solution" would be to generate a spline with many points (some 100 for example) that there the colors would be less likely to go wrong. But this solution can spend a lot of memory if your database is large and will smooth the chart. Ex:

    df2 <- data.frame(spline(df$x, df$y, n = 100*nrow(df)))
    df2$cat <- df2$y>0
    ggplot(data = df, aes(x, y))+ geom_line(data=df2, aes(color=cat, group=1))
    

    inserir a descrição da imagem aqui


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2