4
votes

In ggplot2, I am making a geom_tile plot where both color and alpha vary with the same variable, I would like to make a single guide that shows the colors the way they appear on the plot instead of 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)

This produces a figure with two guides: one for color and one for alpha. I would like to have just one guide on which both color and alpha vary together the way they do in the figure (so as the color shifts to blue, it fades out)

For this figure, I could achieve a similar effect by varying the saturation instead of alpha, but the real project in which I am using this, I will be overlaying this layer on top of a map, and want to vary alpha so the map is more clearly visible for smaller values of the z-variable.

1

1 Answers

2
votes

I don't think you can combine continuous scales into one legend, but you can combine discrete scales. For example:

# 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 z at different, perhaps more convenient, values and change scale_fill_hue to whatever color scale you prefer.

enter image description here