Maximilian
Maximilian

Reputation: 4229

Changing line color according to function

I would like to change the color of a line according to function (so different color for each interval for a given vector length. (20 points = 20 colors)

Sample data and function:

fun <- function(x) {exp(x)}
data <- data.frame(r=seq(0,1,0.1),v=rnorm(11,0,1))

I have tried but this is not what I need.

col.palette <- colorRampPalette(c("darkgreen","yellow","red"), space = "rgb")

plot(fun(sort(data$v)),data$r,type="l",col=col.palette(11)[1])
for (i in seq(2,11)){
     lines(i*fun(sort(data$v)),data$r,col=col.palette(11)[i])}

Here is example what I actually need, but preferably in base R or lattice.

library(ggplot2)

so <- data.frame(x = 1:10,y = 1:10,col = 1:10)
ggplot(so,aes(x = x, y = y)) + geom_line(aes(group = 1,colour = col))

Upvotes: 1

Views: 142

Answers (1)

jbaums
jbaums

Reputation: 27388

You could plot each interval with segments (base) or lsegments (lattice):

  1. base:

    xy <- data.frame(x=sort(runif(11)), y=sort(runif(11)))
    plot(xy, type='n')
    segments(xy[-nrow(xy), 1], xy[-nrow(xy), 2],
             xy[-1, 1], xy[-1, 2], col=rainbow(nrow(xy)-1), lwd=3)
    

    coloured_lines

    Applied to your data:

    xy <- data.frame(x=fun(sort(data$v)), y=data$r)
    plot(xy, type='n', xlab='exp(x)', ylab='r')
    segments(xy[-nrow(xy), 1], xy[-nrow(xy), 2],
             xy[-1, 1], xy[-1, 2], col=col.palette(nrow(xy)-1), lwd=3)
    

    plot2

  2. lattice:

    Much the same...

    xyplot(y~x, data=xy, panel=function(x, y, ...) {
        lsegments(x[-length(x)], y[-length(y)], x[-1], y[-1], 
                  col=col.palette(nrow(xy)-1), lwd=3)
    })
    

    enter image description here

Upvotes: 5

Related Questions