Conditional colouring of a geom_smooth

前端 未结 2 834
星月不相逢
星月不相逢 2021-01-11 19:16

I\'m analyzing a series that varies around zero. And to see where there are parts of the series with a tendency to be mostly positive or mostly negative I\'m plotting a

2条回答
  •  时光取名叫无心
    2021-01-11 19:55

    You may use the n argument in geom_smooth to increase "number of points to evaluate smoother at" in order to create some more y values close to zero. Then use ggplot_build to grab the smoothed values from the ggplot object. These values are used in a geom_line, which is added on top of the original plot. Last we overplot the y = 0 values with the geom_hline.

    # basic plot with a larger number of smoothed values
    p <- ggplot(df, aes(x = x2, y = x1)) +
      geom_line() +
      geom_smooth(linetype = "blank", n = 10000)
    
    # grab smoothed values
    df2 <- ggplot_build(p)[[1]][[2]][ , c("x", "y")]
    
    # add smoothed values with conditional color
    p +
      geom_line(data = df2, aes(x = x, y = y, color = y > 0)) +
      geom_hline(yintercept = 0)
    

提交回复
热议问题