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

5

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 a different color for negative values.

To make a point graph, simply use the command below:

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

However,ifIchangetoalinechartitdoesnotwork.

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

IfItrytodowithggplot2itisnotworkingeither.Itassignsthecolorofthepreviouspointtothelinesegment.

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

How do I correctly assign the red color to negative values and blue color to positive values in the line plot?

    
asked by anonymous 19.03.2014 / 17:49

1 answer

4

A partial "solution" would be to generate a spline with many points (about 100 for example) that the colors would be less likely to be in the wrong place. 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))

    
19.03.2014 / 18:19