Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading