是否可以在R中使用ggplot将颜色渐变应用于geom_smooth? [英] Is it possible to apply color gradient to geom_smooth with ggplot in R?

查看:82
本文介绍了是否可以在R中使用ggplot将颜色渐变应用于geom_smooth?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to apply the scale colour gradient also to the smooth line. At the moment the code below set the color fix to red.

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
 )

但是当我设置color = values时,它不起作用.而是使用默认的蓝色.

But when I set color = values it doesn't work. Instead it takes the default blue.

geom_smooth(
 data = a,
 aes(x = year, y = values, color = values),
 size = 2
 )

谢谢.

推荐答案

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

Use geom_smooth(aes(color=..y..)) to add a color aesthetic to geom_smooth. ..y.. is the vector of y-values internally calculated by geom_smooth to create the regression curve. In general, when you want to add an aesthetic to a summary value that's calculated internally, you need to map the aesthetic to that internal value. Here, the internal value is the ..y.. value of the smoothing function. In other cases it might be ..count.. for histograms or bar plots, or ..density.. for density plots.

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

Here's an example using your data. Note that I've tweaked a few of the plot parameters for illustration.

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

请注意,回归线的颜色变化不大,因为其y值相对于数据而言范围较小.这是另一个带有伪数据的示例,该伪数据会生成范围更广的回归曲线.

Note that the color of the regression line does not change much because its y-values span a small range relative to the data. Here's another example with fake data that generates a more wide-ranging regression curve.

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

这篇关于是否可以在R中使用ggplot将颜色渐变应用于geom_smooth?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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