根据y值连续颜色的geom_line [英] Continuous colour of geom_line according to y value
问题描述
如果你看看这个
ggplot(mtcars,aes(x = disp,y = mpg,color = mpg))+ geom_line()
您将会看到线条颜色根据相应的y值而变化,这就是我想要的,但只是逐节。我希望颜色根据y值连续变化。任何简单的方法?
想到的一种可能是使用插值来创建更多的x值和y值,从而使颜色更连续。我使用 approx
来线性插入给定的数据点。下面是一个简单数据集的例子:
#原始数据和相应的图
df < - data.frame (x = 1:3,y = c(3,1,4))
library(ggplot2)
ggplot(data = df,aes(x = x,y = y,color = y) )+
geom_line(size = 3)
#插值使'更多值和更平滑的颜色梯度
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,color = y))+
geom_line(size = 3)
n 参数中使用 approx
来调整要创建的点数(插值发生在 n
跨越区间[ min(x),max(x)
])的等间隔点。有了更多的值,可能 geom_point
的外观更平滑:
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,color = y))+
geom_point(size = 3)
If you look at this
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?
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)
# 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)
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)
这篇关于根据y值连续颜色的geom_line的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!