Search code examples
rggplot2geom-point

How to set different fill colour for scale guide in geom_jitter?


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


Solution

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