Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Geom_density_2d_filled() ggplot: (1) how to draw a contour around all points, and (2) how to change gradient colors?

Writer 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()

ggplot

(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()

enter image description here

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()

enter image description here

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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.