1

I have the following R code that I am using to plot a set of time series, which are normalised [0,1]. I want each of the lines to have a color intensity such that all values <= 0.5 have shades of blue and > 0.5 have shades of orange/yellow. This is what I have right now:

data <- SOME_DATA

for(i in 1:length(data)){
  y <- data[[paste("I",i,sep = "")]]
  x <- 1:length(y)
  lo <- loess(y~x)
  ylim <- range(seq(-1,1,by=0.5))
  if(i==1){
    plot(x,y,ylim = ylim,main = "Some title",col = ifelse(y[1] < 0,'red','green'),ylab = "intensity",xlab = "time steps")
  }
  lines(predict(lo),lwd=2,ylim = ylim,col = ifelse(y[1] < 0,rgb(1,0,0,0.2),rgb(0,1,0,0.2)))
}

How can I go about achieving what I described above?

Thanks

Bono
  • 4,757
  • 6
  • 48
  • 77
user3259045
  • 89
  • 1
  • 5
  • You are just using base r functionality. No need for `plotly` in this example. I gave you an answer below. I hope this helps. Otherweise you have to provide more specific example.data so that we can run your code. – jakob-r Aug 27 '16 at 11:05
  • Edited - sorry it seems like I was using it for some other code below in the script.. – user3259045 Aug 27 '16 at 16:07

2 Answers2

2

Using this solution you can do the following:

data <- data.frame(x= runif(100), y = runif(100))
color.gradient <- function(x, colors=c("blue","white","red"), colsteps=100) {
  return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
plot(data$x, data$y, col= color.gradient(data$x))

R plot preview

Community
  • 1
  • 1
jakob-r
  • 6,824
  • 3
  • 29
  • 47
0

Slightly more configurable image may be possible with ggplot. Using data and color.gradient from @jakobr :

ggplot(data, aes(x, y))+ geom_point(col=color.gradient(data$x))+ theme_bw()

enter image description here

rnso
  • 23,686
  • 25
  • 112
  • 234
  • This is not a very good practice. If you are using ggplot2 then you should definitely make use of `ggplot(data, aes(x = x, y = y, color = x)) + geom_point() + scale_colour_gradient2(low = "blue", mid = "white", high = "red")`! – jakob-r Aug 29 '16 at 09:38