Conditional colouring of a geom_smooth

前端 未结 2 818
星月不相逢
星月不相逢 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)
    

    0 讨论(0)
  • 2021-01-11 19:58

    Something like this:

    # loess data
    res <- loess.smooth(df$x2, df$x1)
    res <- data.frame(do.call(cbind, res))
    
    res$posY <- ifelse(res$y >= 0, res$y, NA)
    res$negY <- ifelse(res$y < 0, res$y, NA)
    
    # plot
    ggplot(df, aes(x = x2, y = x1)) + 
      geom_hline() + 
      geom_line() + 
      geom_line(data=res, aes(x = x, y = posY, col = "green")) +
      geom_line(data=res, aes(x = x, y = negY, col = "red")) +
      scale_color_identity()
    

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