1

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))

enter image description here

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))

enter image description here

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:

enter image description here

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!

Tom
  • 73
  • 1
  • 6
  • 2
    Possible duplicate of [Multiple legends for a ggplot in R](https://stackoverflow.com/questions/46975531/multiple-legends-for-a-ggplot-in-r) – Ankur Sinha Mar 06 '18 at 12:00

1 Answers1

0

Please add the code

aes(color = z_rescale) +
scale_color_gradient(low = "blue", high = "red") +

after geom_tile() line and you will get the desired output

YBS
  • 19,324
  • 2
  • 9
  • 27