ggplot2: Is it possible to combine color/fill and size legends?

Hi @RuReady! Normally, guides (a catch-all term for legends, colour bars and other visual demonstrations of scale on the plot) combine automatically, and you can nudge things along by explicitly giving their associated scales the same name.

But in this case the legends are different types by default: the fill guide is a "colourbar", and the size guide is a "legend" (NB: a legend in ggplot2 is a type of guide that shows the scale at a few discrete levels). You'll have to get them to agree on a guide type in order to combine them.

Since it doesn't really make sense to have a continuous guide like a colour bar for size, you'll probably have to go the other way and force the fill scale to use a legend:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.1

p <- ggplot(mtcars, aes(wt, mpg))

p + geom_point(aes(size = qsec, fill = qsec), shape = 21, alpha = 0.7) +
  scale_fill_viridis_c(guide = "legend") +
  scale_size_continuous(range = c(1, 15))

Created on 2018-10-26 by the reprex package (v0.2.0).

I hope that does what you want! :slight_smile:

7 Likes