在R中使用ggplot2改变渐变 [英] Varying gradient using ggplot2 in R

查看:117
本文介绍了在R中使用ggplot2改变渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个绘图,其中颜色梯度同时沿x和y轴变化.更具体地说,我正在尝试设置渐变,以使色相范围沿x轴变化,而值沿y轴变化.

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.

例如,我正在处理正弦曲线,该噪声沿 -pi pi 带有一些噪声.

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()

现在,我想给线着色,以使色相沿x轴从红橙色到橙黄色再到黄绿色等,然后​​根据其y值在该范围内采用不同的值.因此,在 x = 0时,在 x = -pi 处, y = 2 可能是红色,而在 x == 0时, y = -2 可能是黄色. y = 2 可能是绿色,而 y = -2 可能是蓝色.

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?

推荐答案

以下是使用根据x和y计算出的色相进行选择的一种选择:

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()

请注意,因为垂直方向上的线条很长,所以效果无法完全看到.这是使用 approx 进行插值的版本:

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()

在两种情况下,色调都取决于 x y ,并且值保持恒定.如果您的原始说明不正确,那么这符合您提出的示例.显然,可以对它进行定制以分别改变其色相和价值.还值得注意的是,需要设置一个 group 组.否则, ggplot2 尝试将相同颜色的所有点连接在一起.

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.

这篇关于在R中使用ggplot2改变渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆