Combine guides for continuous fill (color) and alpha scale

In ggplot2, I make a chart geom_tilewhere both color and alpha change with the same variable, I would like to make one guide that shows the colors as they appear on the chart, and not two separate guides.

library(ggplot2)

x <- seq(-10,10,0.1)
data <- expand.grid(x=x,y=x)
data$z <- with(data,y^2 * dnorm(sqrt(x^2 + y^2), 0, 3))
p <- ggplot(data) + geom_tile(aes(x=x,y=y, fill = z, alpha = z))
p <- p + scale_fill_continuous(low="blue", high="red") + scale_alpha_continuous(range=c(0.2,1.0))
plot(p)

The result is a figure with two guides: one for color and one for alpha. I would like to have only one guide, on which both colors and alpha change together as they do in the picture (since the color shifts to blue, it disappears)

For this figure, I could achieve a similar effect by changing the saturation instead of alpha, but the real project in which I use this, I will overlay this layer on top of the map and want to vary the alpha, so the map is more clearly visible for lower values โ€‹โ€‹of the z-variable.

+4
source share
1 answer

I do not think that you can combine continuous scales into one legend, but you can combine discrete scales. For instance:

# Create discrete version of z
data$z.cut = cut(data$z, seq(min(data$z), max(data$z), length.out=10))

ggplot(data) +  
  geom_tile(aes(x=x, y=y, fill=z.cut, alpha=z.cut)) +
  scale_fill_hue(h=c(-60, -120), c=100, l=50) +
  scale_alpha_discrete(range=c(0.2,1))

You can, of course, cut zat different, possibly more convenient values, and change scale_fill_hueto any color scheme that you prefer.

enter image description here

+2
source

Source: https://habr.com/ru/post/1546388/


All Articles