Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuous colour of geom_line according to y value

Tags:

r

ggplot2

If you look at this

enter image description here

ggplot(mtcars,aes(x=disp,y=mpg,colour=mpg))+geom_line()

you will see that the line colour varies according to the corresponding y value, which is what I want, but only section-by-section. I would like the colour to vary continuously according to the y value. Any easy way?

like image 444
Steve Powell Avatar asked Sep 18 '14 06:09

Steve Powell


Video Answer


1 Answers

One possibility which comes to mind would be to use interpolation to create more x- and y-values, and thereby make the colours more continuous. I use approx to " linearly interpolate given data points". Here's an example on a simpler data set:

# original data and corresponding plot
df <- data.frame(x = 1:3, y = c(3, 1, 4))
library(ggplot2)
ggplot(data = df, aes(x = x, y = y, colour = y)) +
  geom_line(size = 3)

enter image description here

# interpolation to make 'more values' and a smoother colour gradient 
vals <- approx(x = df$x, y = df$y)
df2 <- data.frame(x = vals$x, y = vals$y)

ggplot(data = df2, aes(x = x, y = y, colour = y)) +
  geom_line(size = 3)

enter image description here

If you wish the gradient to be even smoother, you may use the n argument in approx to adjust the number of points to be created ("interpolation takes place at n equally spaced points spanning the interval [min(x), max(x)]"). With a larger number of values, perhaps geom_point gives a smoother appearance:

vals <- approx(x = df$x, y = df$y, n = 500)
df2 <- data.frame(x = vals$x, y = vals$y)
ggplot(data = df2, aes(x = x, y = y, colour = y)) +
  geom_point(size = 3)
like image 151
Henrik Avatar answered Nov 19 '22 16:11

Henrik