Geom_Density_2D_Filled() Ggplot: (1) How to Draw a Contour Around All Points, and (2) How to Change Gradient Colors?

Geom_Density_2D_Filled() Ggplot: (1) How to Draw a Contour Around All Points, and (2) How to Change Gradient Colors?

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.