How to reproduce smoothScatter's outlier plotting in ggplot?

前端 未结 2 1026
终归单人心
终归单人心 2021-02-02 17:35

I am trying to get something like what the smoothScatter function does, only in ggplot. I have figured out everything except for plotting the N most sparse points.

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-02 18:06

    Here is a workaround of sorts! Is doesn't work on the least dense n points, but plots all points with a density^0.25 less than x.

    It actually plots the stat_density2d() layer, then the geom_point(, then the stat_density2d(), using alpha to create a transparent "hole" in the middle of the last layer where the density^0.25 is above (in this case) 0.4.

    Obviously you have the performance hit of running three plots.

    # Plot the ggplot version
    ggplot(mydata) + aes(x=x, y=y) + scale_x_log10() + scale_y_log10() + 
      stat_density2d(geom="tile", aes(fill=..density..^0.25, alpha=1), contour=FALSE) + 
      geom_point(size=0.5) +
      stat_density2d(geom="tile", aes(fill=..density..^0.25,     alpha=ifelse(..density..^0.25<0.4,0,1)), contour=FALSE) + 
      scale_fill_gradientn(colours = colorRampPalette(c("white", blues9))(256))
    

    enter image description here

提交回复
热议问题