0

I'm running ggplot2 v3.4.1. I created this 2 legend plot that by default it is placing the year2 size legend below the cty color legend. However, I would like the size legend to be on top.

library(tidyverse)

mpg$year2 = factor(mpg$year)
values = c(2,4); names(values) = c("1999", "2008")
p = mpg %>%
  ggplot(aes(x = cty, y = hwy, color = cty, size = year2)) + 
  geom_point() +
  scale_size_manual(name = "year2", values = values)
p

continuous

Therefore, I used guides() to specify the legend ordering but it changes the continuous color legend cty to discrete

p + guides(size = guide_legend(order = 1), 
           color = guide_legend(order = 2))

discrete

I saw this post ggplot guide_legend argument changes continuous legend to discrete but am unable to figure out how to use guide_colorbar() when you have 2 or more legends.

How do I change my code to keep the cty legend as continuous? Thx

pcantalupo
  • 2,212
  • 17
  • 27

1 Answers1

1

It's simply

p + guides(size = guide_legend(order = 1), 
           color = guide_colorbar(order = 2))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • I didn't realize colorbar was a drop in replacement for guide_legend. Spent all morning trying to figure this out. Thank you – pcantalupo Jun 03 '23 at 18:53