简体   繁体   中英

Varying gradient using ggplot2 in R

I am trying to create a plot where the color gradient changes by both the x and y axis. More specifically I am trying set up the gradients so that the hue range changes along the x axis and the value changes along the y axis.

For an example I am working with a sine curve with some noise along -pi to pi .

set.seed(5678)
x <- seq(-1*pi, 1*pi, 0.01)
y <- sin(x) + rnorm(length(y))
df <- cbind.data.frame(x, y)
ggplot(df, aes(x=x, y=y)) + geom_line()

Now I want to colorize the line so that the hue progresses from red-orange to orange-yellow to yellow-green, etc. along the x axis and then will take on different values in that range depending on its y value. So at x=-pi , y=2 might be red and y=-2 might be yellow while at x=0 , y=2 might be green and y=-2 might be blue.

Has anyone tried to create a graph like this?

Here's an option for doing it using a hue calculated from x and y:

df$hue <- pmax(pmin((df$x + pi)/pi/3 + (2 - df$y) / 12, 1), 0)
ggplot(df, aes(x=x, y=y, group = 1, colour = hsv(hue, 1, 1))) + geom_path() +
  scale_colour_identity()

Note because the lines are quite long vertically so the effect isn't fully seen. Here's a version using approx to interpolate:

adf <- as.data.frame(approx(df, xout = seq(-pi, max(df$x), 0.001)))
adf$hue <- pmax(pmin((adf$x + pi)/pi/3 + (2 - adf$y) / 12, 1), 0)
ggplot(adf, aes(x=x, y=y, group = 1, colour = hsv(hue, 1, 1))) + geom_path() +
  scale_colour_identity()

色相图

In both cases, it's the hue that's dependent on both x and y , with value held constant. That fits your proposed example, if not your original description. Clearly it could be tailored to vary hue and value separately. It's also worth noting that there needs to be a group set. Otherwise ggplot2 tries to join together all the points of the same colour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM