ggplot2 legend not combining (color & size aes for the same variable)

Hey everyone,

I ran into an issue that I'd like to fix and understand.

I am using the same variable in two aesthetics (color and size), but I'd like them to be combined in the legend. All the help I've found seems to indicate that what I've done should work, and I'd like to understand why it is not combing the legends.

Here is a simple example:

df <- tibble(regShare = c(9.09,42.42,33.33,37.5,50.57,22,40.47),
             n.reg = c(9,14,1,3,44,16.42,17),
             Score = c(11.2,45.7,32.2,28.2,69.6,36.3,42.1))

ggplot(df) +
  aes(x = regShare,
      y = Score) +
  geom_point(aes(size = n.reg,
                 color = n.reg)) +
  scale_color_continuous(limits=c(0, 60), breaks=seq(0, 60, by=15),
                         type = "viridis") +
  scale_size_continuous(limits=c(0, 60), breaks=seq(0, 60, by=15))

The main answer I've found online (e.g. R Cookbook which says " If you use both colour and shape , they both need to be given scale specifications. Otherwise there will be two two separate legends." is what I've done my best to implement above. I still get two legends:

image

One thing I've noticed is the scales are revered (0:60, 60:0), so I tried:
scale_size_continuous(limits=c(0, 60), breaks=seq(60, 0, by=-15))

While this makes the scales appear in the same order in the legend, but I still have two separate legends.

What else am I missing?

(by the way, this is R3.6.3 with ggplot2 3.3.5)

Bonus question:
I'd like to use the "plasma palette/option in viridis. How could I do this in the scale_size_continuous() above? If I include scale_color_viridis_c(option = "plasma") it overrides the previous scale argument.

Thank you!

This is not very intuitive but you need to set the guide argument to "legend"

library(tidyverse)

df <- tibble(regShare = c(9.09,42.42,33.33,37.5,50.57,22,40.47),
             n.reg = c(9,14,1,3,44,16.42,17),
             Score = c(11.2,45.7,32.2,28.2,69.6,36.3,42.1))

ggplot(df) +
    aes(x = regShare,
        y = Score) +
    geom_point(aes(size = n.reg, color = n.reg)) +
    scale_color_continuous(guide = "legend", limits=c(0, 60), breaks=seq(0, 60, by=15),
                       type = "viridis") +
    scale_size_continuous(limits=c(0, 60), breaks=seq(0, 60, by=15))

Created on 2021-12-19 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.