Continuous colour of geom_line according to y value

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)

Since ggplot2 v0.8.5 one can use geom_line or geom_path with different lineend options (right now there are three options: round, butt and square). Selection depends on the nature of the data.

round would work on sharp edges (like in given OPs data):

library(ggplot2)
ggplot(mtcars, aes(disp, mpg, color = mpg)) +
  geom_line(size = 3, lineend = "round")

enter image description here

square would work on a more continuous variable:

df <- data.frame(x = seq(0, 100, 10), y = seq(0, 100, 10) ^ 2)
ggplot(data = df, aes(x = x, y = y, colour = y)) +
  geom_path(size = 3, lineend = "square")

enter image description here

Tags:

R

Ggplot2