Sunday, June 26, 2022

[FIXED] How can I delete the background in stat_density_2d?

Issue

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

You could map the density to the alpha scale so that lower values are transparent:

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, alpha = ..density..*10e04), 
                  contour = FALSE, 
                  h = c(7, 7),
                  n = 300) +
  scale_alpha_continuous(range = c(0, 1), limits = c(0, 3), 
                         guide = guide_none()) +
  ggtitle("7387") + 
  theme(plot.title = element_text(lineheight=.8, face="bold"))+
  scale_y_reverse() +
  scale_fill_viridis_c(limits = c(0, 12))

enter image description here



Answered By - Allan Cameron
Answer Checked By - Gilberto Lyons (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.