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
Thank you.
I would use
geom_raster
here withstat = '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: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: