'How can I delete the background in stat_density_2d?

I am trying to make density maps in R using the function stat_density_2d, but I would like to remove the background color for which the density is null. I tried changing the limits for the density, but when moving the limits from [0,5] to [0.1, 5], the background becomes grey instead of dark blue. What can I do to have a transparent background, and colouring only the datapoints?

Here is my code :

ggplot(TEST, aes(x = X, y = Y)) +
  geom_point() +
  stat_density_2d(geom = "raster", aes(fill = ..density..*10e04), contour = F, 
                  h = c(5, 5),
                  n = 300) +
  ggtitle("7387")+ 
  theme(plot.title = element_text(lineheight=.8, face="bold"))+
  scale_y_reverse()+
  scale_fill_distiller(palette = 'Spectral', limits=c(0,5))

enter image description here

Thank you!



Solution 1:[1]

Building on the accepted answer -- the background goes grey when setting the limits because coordinates falling outside the limits receive a value of NA, and the default fill for NA is "grey50". To use a different color, specify na.value. For removing the background, set the lower limit to some value near 0 and then use "transparent"

library(ggplot2)

TEST <- data.frame(X = rnorm(10000, -700, 50),
                   Y = rnorm(10000, -450, 50))

ggplot(TEST, aes(x = X, y = Y)) +
  stat_density_2d(geom = "raster", 
                  aes(fill = ..density..*10e04), 
                  contour = FALSE, 
                  h = c(7, 7),
                  n = 300) +
  ggtitle("7387") + 
  theme(plot.title = element_text(lineheight=.8, face="bold"))+
  scale_y_reverse() +
  scale_fill_viridis_c(limits = c(0.001, 12), na.value = "transparent")

Created on 2022-05-22 by the reprex package (v2.0.1)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Patrick Sadil