I'm using ggplot to create a heat-map style plot, and would like to add a second legend with the data scaled a different way. I'm wondering if there is a simple way to do this.
I do not believe that this is a duplicate of other "multiple legends" questions e.g. Multiple legends for a ggplot in R as crucially I want to add extra legends for the same aesthetic - i.e. one aesthetic mapping, two legends.
Example code
# Create a dataframe with some dummy data
x <- c()
y <- c()
for(i in 1:100){
for(j in 1:100){
x <- c(x, i)
y <- c(y, j)
}
}
example_data <- data.frame(x, y)
example_data$z <- example_data$x*example_data$y
example_data$z_rescale <- example_data$z*0.5
Now we've got some data that I'd like to plot as a heatmap with "z" as a colour gradient.
ggplot(example_data, aes(x = x, y = y, fill = z)) +
geom_tile() +
scale_fill_gradient(low = "blue", high = "red") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
Doing the same with the rescaled z gives an identical plot, but with the rescaled legend:
ggplot(example_data, aes(x = x, y = y, fill = z_rescale)) +
geom_tile() +
scale_fill_gradient(low = "blue", high = "red") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
What I'd like to do however is have a single plot showing the two different legends, which would look something like this mock-up:
Now, I imagine this would be possible by creating two plots, finding the grob that represents the legend in one of the plots and cunningly adding it to the second plot... however, is there a much simpler way that I'm overlooking?
Many thanks!