Color points by density with ggplot2
A code snippet that shows how to color points by density in R with ggplot2.
Load libraries, define a convenience function to call MASS::kde2d, and generate some data:
Notice how the points are overplotted, so you can’t see the peak density:
Here, we split the plot into a 100 by 100 grid of squares and then color the
points by the density in each square. I recommend viridis for the color
Here’s what happens when you set
n = 15 (the squares in the grid are too big):