Geom_density_2d_filled() ggplot: (1) how to draw a contour around all points, and (2) how to change gradient colors?
Andrew Henderson
I have two questions that I couldn't figure our google out:
Data and ggplot:
x = rnorm(n = 500, mean = 0.5, sd = 0.3)
y = rnorm(n = 500, mean = 6, sd = 1)
data = merge(x, y, by = "row.names", all = TRUE)
data %>% ggplot(aes(x, y))+ geom_density_2d_filled(contour_var = "ndensity", bins = 5)+ theme_classic()(1) how to draw a contour around all points? Currently, 20% of values has the same colour as the background. New layer should be added?
(2) how to change background colour to white and gradient colour to brewer "Blues" palette (all values above 0 should have distinct blue colour from white background)?
2 Answers
You'd probably want to decouple the stat from the geom, as the geom_density_2d_filled() draws polygons but also includes the outer layer as a rectangle.
Here is my suggestion:
x = rnorm(n = 500, mean = 0.5, sd = 0.3)
y = rnorm(n = 500, mean = 6, sd = 1)
data = merge(x, y, by = "row.names", all = TRUE)
data %>% ggplot(aes(x, y))+ stat_density_2d(geom = "polygon", contour = TRUE, aes(fill = after_stat(level)), colour = "black", bins = 5) + scale_fill_distiller(palette = "Blues", direction = 1) + theme_classic() 4 Thanks to teunbrand! But the points are still outside the contours.
set.seed(2)
data %>% ggplot(aes(x, y))+ stat_density_2d(geom = "polygon", contour = TRUE, aes(fill = after_stat(level)), colour = "black", bins = 5)+ geom_point()+ scale_fill_distiller(palette = "Blues", direction = 1) + theme_classic() 1