Search code examples
rggplot2legend

ggplot - ordering legends with guides changes continuous legend to discrete


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


Solution

  • It's simply

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

    enter image description here