R ggplot2 - 具有第三个连续变量的渐变颜色的geom_smooth [英] R ggplot2 - geom_smooth with gradient color from a third continuous variable

查看:1883
本文介绍了R ggplot2 - 具有第三个连续变量的渐变颜色的geom_smooth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法绘制平滑曲线(x = var1,y = var2)并将其与第三个连续变量(z = var3)相对照?我使用下面的代码:

  library(ggplot2)

x = runif(100,-20 ,20)
y = 2 * x + x ^ 2 + rnorm(100,0,50)
z = 0.5 * x + rnorm(100,0,2)
df = data.frame (x = x,y = y,z = z)

ggplot(data = df,aes(x = x,y = y))+ geom_smooth(method ='loess',aes(color = z),se = F)

然而,平滑的线仍然是纯蓝的。



使用内部变量..y ..而不是var3颜色相对于var2的线。

  ggplot(data = df,aes(x = x,y = y))+ geom_smooth(method ='loess',aes(color = .. y,)se = F)

是否有另一个内部变量需要调用才能使var3的颜色变为线?



我可以用 geom_line 生成所需的图表,但我希望将它平滑化。

解决方案

你在正确的轨道上使用 geom_line ,you j你需要在预先平滑的数据上使用它。然后按照上面的数据框,然后:

pre $ df $ predict < - 预测(黄色(y〜x,数据= df) )

ggplot(df,aes(x = x,y = predict))+
geom_line(aes(color = z))

如果您的 x 存在较大差距,则可能会产生丑陋的结果;他们会以点之间的平坦部分出现。通过提供 newdata = predict()并将其存储在第二个数据框中,还需要为这些新的 x 值重新计算 z




Is there a way to plot a smoothed curve (x=var1, y=var2) and color it with respect to a third continuous variable (z=var3)? I am using the following code:

    library(ggplot2)

    x = runif(100,-20,20)
    y = 2*x+x^2+rnorm(100,0,50)
    z = 0.5*x+rnorm(100,0,2)
    df = data.frame(x=x,y=y,z=z)

    ggplot(data=df,aes(x=x,y=y))+geom_smooth(method='loess', aes(color=z),se=F) 

However, the smoothed line is still solid blue.

Using the internal variable "..y.." instead of var3 colors the line with respect to var2.

    ggplot(data=df,aes(x=x,y=y))+geom_smooth(method='loess', aes(color=..y..),se=F) 

Is there another internal variable to call in order to color the line with respect to var3?

I am able to generate the desired plot with geom_line, but I would like to have it smoothed instead.

解决方案

You're on the right track using geom_line, you just need to use it on pre-smoothed data. Take your dataframe as above, then:

df$predict <- predict(loess(y~x, data = df))

ggplot(df, aes(x = x,y = predict)) +
  geom_line(aes(colour = z)) 

This can generate ugly results if your x has big gaps; they'll come out as flat segments between points. There are workarounds for that by feeding newdata= to predict() and storing it in a second dataframe, but then you need to also recalculate z for those new x values.

这篇关于R ggplot2 - 具有第三个连续变量的渐变颜色的geom_smooth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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