thomasp85 / ggforce

Accelerating ggplot2
https://ggforce.data-imaginist.com
Other
917 stars 105 forks source link

Feature Request: geom_points colored by density #116

Closed bjreisman closed 4 years ago

bjreisman commented 5 years ago

(Originally proposed for in ggplot2 as issue 3150)

One geom/stat which would be very useful is a hybrid between geom_density_2d and geom_point, where points are colored by their density. This would help avoid overcome overplotting by mapping the density to the color aesthetic, while preserving the individual points in areas of low density. This type of visualization is very common in flow cytometry, but could be useful elsewhere as well.

@slowkow has an excellent example of how to achieve the desired effect here, but it requires computing the density at each point prior to plotting, which becomes burdensome for faceted plots.

I was able to modify the stat_density_2d function slightly using @slowkow's code as a guide to make a new stat_density_point_2d function which worked well in my hands(example below), but I had trouble writing the corresponding geom. Is this something that could be considered for inclusion in ggforce?

I'd be happy to contribute my version, thought there may be a better way to achieve the same goal.

Thanks for your consideration!

library(ggplot2)
dat <- data.frame(
  x = c(
    rnorm(1e4, mean = 0, sd = 0.1),
    rnorm(1e3, mean = 0, sd = 0.1)
  ),
  y = c(
    rnorm(1e4, mean = 0, sd = 0.1),
    rnorm(1e3, mean = 0.1, sd = 0.2)
  )
)

ggplot(dat, aes(x, y)) +
  stat_identity() +
  scale_color_viridis_c() +
  theme_classic()

stat_identity

ggplot(dat, aes(x, y)) +
   stat_density_point_2d() +
   scale_color_viridis_c() +
   theme_classic()

stat_density_point_2

thomasp85 commented 4 years ago

Did you end up making a package for this (I faintly remember seeing something for that). If not I'll happily accept a PR

bjreisman commented 4 years ago

I did not, but @LKremer did as a standalone package: https://github.com/LKremer/ggpointdensity Thanks for considering it!