gpt4 book ai didi

r - 是否可以在R中使用ggplot将颜色渐变应用于geom_smooth?

转载 作者:行者123 更新时间:2023-12-04 17:16:57 25 4
gpt4 key购买 nike

我想将刻度颜色渐变也应用到平滑线。
目前,以下代码将颜色固定设置为红色。

library(ggplot2)
a <- data.frame(year = 1:100, values = sin(1:100)*1000 + runif(100))
ggplot(a, aes(x = year, y = values, color = values )) + geom_line(size = 2) +
scale_colour_gradient2(
low = "blue",
mid = "white" ,
high = "red",
midpoint = 10
)+
geom_smooth(
data = a,
aes(x = year, y = values),
color = "red",
size = 2
)

enter image description here

但是,当我设置 color = values时,它不起作用。相反,它采用默认的蓝色。
geom_smooth(
data = a,
aes(x = year, y = values, color = values),
size = 2
)

enter image description here

提前致谢。

最佳答案

使用geom_smooth(aes(color=..y..))geom_smooth添加色彩美感。 ..y..geom_smooth内部计算以创建回归曲线的y值的向量。通常,当您要将美学添加到内部计算的汇总值时,需要将美学映射到该内部值。在此,内部值为平滑函数的..y..值。在其他情况下,对于直方图或柱状图,可能是..count..;对于密度图,可能是..density..

这是使用您的数据的示例。请注意,我已经调整了一些绘图参数以进行说明。

set.seed(48)
a <- data.frame(year = 1:100, values = sin(1:100)*1000 + runif(100))

ggplot(a, aes(x = year, y = values, color = values )) +
geom_line(size = 0.5) +
geom_smooth(aes(color=..y..), size=1.5, se=FALSE) +
scale_colour_gradient2(low = "blue", mid = "yellow" , high = "red",
midpoint=10) +
theme_bw()

enter image description here

请注意,回归线的颜色变化不大,因为其y值相对于数据而言范围较小。这是另一个带有伪数据的示例,该伪数据会生成范围更广的回归曲线。
set.seed(1938)
a2 <- data.frame(year = seq(0,100,length.out=1000), values = cumsum(rnorm(1000)))

ggplot(a2, aes(x = year, y = values, color = values )) +
geom_line(size = 0.5) +
geom_smooth(aes(color=..y..), size=1.5, se=FALSE) +
scale_colour_gradient2(low = "blue", mid = "yellow" , high = "red",
midpoint=median(a2$values)) +
theme_bw()

enter image description here

关于r - 是否可以在R中使用ggplot将颜色渐变应用于geom_smooth?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37241893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com