R ggplot2 - geom_smooth with gradient color from a third continuous variable

前端 未结 1 1246
梦毁少年i
梦毁少年i 2021-01-25 20:41

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:

    li         


        
相关标签:
1条回答
  • 2021-01-25 21:06

    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.

    0 讨论(0)
提交回复
热议问题