How to Change line chart color according to X value in r

438 Views Asked by At

I have tried this and its changing the graph color based on levels corresponding to Y-axis. Is it possible to do the same but the graph should change the color based on the levels corresponding to X-axis values?

`

library(plotrix)
library(RColorBrewer)
my_colors = brewer.pal(8, "Set2") 
x<-seq(1,100)
y<-sin(x/5)+x/20
par(mar=c(4,4,2,2))
clplot(x, y, main="", lty = 5,lwd=5, levels=c(1,2,3,4,5), col=my_colors, showcuts=T , bt='n')

`

Image

1

There are 1 best solutions below

0
tpetzoldt On

Here an example with base graphics. Function segments(x0, y0, x1 = x0, y1 = y0, col ....) draws lines from each x0, y0 to the next corresponding x1, y1, where we need to remove the first element from x0and the last element from x1:

library(RColorBrewer)
ncol <- 8
my_colors <- brewer.pal(ncol, "Set2") 
x <- 1:100
y <- sin(x/5) + x/20

plot(x, y, type="n")
n <- length(x)
segments(x[-1], y[-1], x[-n], y[-n], col=my_colors[ceiling(ncol * x[-1]/max(x))], lwd=2)

Continuous colors would also be possible.