eliocamp / ggnewscale

Multiple Fill, Color and Other Scales in `ggplot2`
https://eliocamp.github.io/ggnewscale/
GNU General Public License v3.0
406 stars 18 forks source link

How to adjust order of legend items with multiple legends #11

Closed Drosof closed 5 years ago

Drosof commented 5 years ago

Hi, thanks for the great package! I was wondering how to specify the order of legend items using multiple legends. I have 2 fill scales and I cannot adjust the ordering using guides(fill = guide_legend(order = 1). Is there a way to differentiate between the 2 fill levels?

eliocamp commented 5 years ago

I don't have a computer handy right now, but I believe that you can specify guides within the scale_fill() call. So something like:

ggplot(...) +
  ... +
  scale_fill_brewer(..., guide = guide_legend(order = 1)) +
  new_scale_fill() +
  ... +
  scale_fill_viridis(..., guide = guide_legend(order = 2))

Should work.

Drosof commented 5 years ago

Yeah, it seems to work. Thanks

eliocamp commented 5 years ago

Fantastic!

M-Harrington commented 4 years ago

This also worked for me. Oddly, when I ran new_scale in a for loop the two legends changed position in nearly every graph. Is it worth setting a default order to override the algorithm that determines order in ggplot? I'm not sure what in the underlying function was causing the issue though. (excellent package btw, muchas gracias!)

eliocamp commented 4 years ago

ggnewscale doesn't have any control over how ggplot renders the guides. If you try using the same code but without ggnewscale (e.g. using two guides such as colour and fill), does the order of the guides also change?

M-Harrington commented 4 years ago

Oh that's a good point, I forgot that ggplot handles the guides. And yes, it looks like the behavior continues after changing to scale_color_gradient and scale_fill_gradient and removing new_scale(). I'm also using geom_sf for both calls, but I'm not sure that matters.

eliocamp commented 4 years ago

Ah, then it's something on ggplot2's side. Unfortunately I don't have much if any insight into how it handles the ordering of guides (IIRC even the documentation states that is a "secret algorithm" 😂). My first instinct would be to increase the separation between the numbers (order = 1 and order = 99, or something like that).