R: how to combine color gradient on y-axis with density map?

197 views Asked by At

Is it possible to combine a density 2D map, showing color intensity depending on the density of points values, with a color gradient related to y-axis? In other words on the following example, is it possible to choose a color_gradient from red for high y values to blue for low y values, but keeping the intensity of the color as given by the density background?

Here is the code:

x_values <- c(3,3,7,10)
y_values <- c(1.6,1.6,0.2,0.3)

sample_data <- data.frame(x_values = x_values, y _values = y_values)

ggplot(sample_data, aes(x_values, y_values), 
       color.gradient()) +                     # does not have any effect 
      scale_color_gradient(low="blue",high="red")+ # does not have any effect
       stat_density2d(geom="tile", aes(fill = ..density..), contour = FALSE) + 
       geom_point(colour = "white") `

and the corresponding plot

plot to change

Thank you.

1

There are 1 answers

0
Allan Cameron On

I would use geom_raster here with stat = 'density2d'. Map the fill to the computed y value and the alpha channel to the computed density. It's probably best to use a white background to get the full effect:

ggplot(sample_data, aes(x_values, y_values)) +
  scale_fill_gradient(low = "blue", high = "red") +
  geom_raster(stat = 'density2d',
            aes(fill = after_stat(y), alpha = after_stat(density)), 
            na.rm = TRUE) + 
  geom_point(colour = "white") +
  lims(x = c(0, 12), y = c(0, 2)) +
  theme_bw(base_size = 16)

enter image description here

An alternative if you want to specify the low density and high density colors for the y axis is to draw all the low colors on first, then use ggnewscale::new_scale_fill and use the same alpha / fill trick as above:

ggplot(sample_data, aes(x_values, y_values)) +
  geom_raster(stat = 'density2d', aes(fill = after_stat(y)), na.rm = TRUE) +
  scale_fill_gradient(low = "#E0E0FF", high = "#FFE0E0") +
  ggnewscale::new_scale_fill() +
  scale_fill_gradient(low = "blue3", high = "red") +
  geom_raster(stat = 'density2d',
            aes(fill = after_stat(y), alpha = after_stat(density)), 
            na.rm = TRUE) + 
  geom_point(colour = "white") +
  lims(x = c(0, 12), y = c(0, 2)) +
  theme_bw(base_size = 16) +
  theme(legend.position = 'none')

enter image description here