2

I want to create a plot where the geom_points (or jitters) are filled after a given value, but their line color is white.

However, setting colour to white makes it so the legend shows invisible points, and is rather useless. How can I force the legend to display black points with the correct size, but the actual plot has different colour and fill?

An example of what I have gotten to work:

mtcars %>% 
  ggplot(aes(disp, mpg, size = cyl, fill = mpg)) +
  geom_jitter(alpha = 0.8, pch = 21) +
  scale_size_continuous(trans = 'log10') +
  scale_fill_viridis_c()

How can i set color = 'white' inside geom_jitter, without creating a useless legend?

enter image description here

helge
  • 23
  • 5

1 Answers1

2

You can override specific aesthetics in the legend of a scale by using guide_legend(override.aes = list(...)). Example below:

library(ggplot2)

ggplot(mtcars, aes(disp, mpg, size = cyl, fill = mpg)) +
  geom_jitter(alpha = 0.8, pch = 21, colour = "white") +
  scale_size_continuous(
    trans = 'log10',
    guide = guide_legend(override.aes = list(fill = "black"))
  ) +
  scale_fill_viridis_c()

Created on 2021-05-26 by the reprex package (v1.0.0)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • is there an opinion how these 2 legends would be forced to display `fill` and `size` at the same time? – bird May 26 '21 at 09:47
  • Brilliant, this was exactly what I was looking for! Thank you very much! – helge May 26 '21 at 09:48
  • 1
    @bird you can only merge legends if they have the same properties (titles, breaks, labels, etc.). The easiest way to do this is to set the aesthetics to the same column, i.e. `aes(size = var, fill = var)`. Because the fill here is continuous, you should then set the guide to a legend instead of the default colourbar. – teunbrand May 26 '21 at 09:51