clauswilke / relayer

Rethinking layers in ggplot2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Changing the ordering of legends

gabraham opened this issue · comments

Hi,

I'm trying to control the order the of the two legends, but it seems that there is some internal (lexicographical?) ordering going on such that "Legend B" will always appear above "Legend A", regardless of which aesthetic the text is assigned to.

Thanks,
Gad

library(relayer)
#> Note: The package "relayer" is highly experimental. Use at your own risk.
library(ggplot2)
library(magrittr)
library(reprex)

d <- data.frame(x=1:5, y=1:5, p=1:5, pfac=factor(1:5))
lab <- 1:5
g1 <- ggplot(d, aes(x=x, y=y))
g1 <- g1 + geom_line(aes(y=y))
g1 <- g1 + theme(legend.position=c(0.18, 0.55),
                 legend.background=element_rect(fill=alpha("white", 0.1)))
g1 <- g1 + geom_area(aes(fill=pfac))
g1 <- g1 + geom_area(aes(fill2=pfac)) %>% rename_geom_aes(new_aes=c("fill"="fill2"))
#> Warning: Ignoring unknown aesthetics: fill2
g1 <- g1 + scale_fill_manual(aesthetics="fill", name="Legend B",
   values=1:5, labels=lab)
g1 <- g1 + scale_fill_manual(aesthetics="fill2", name="Legend A",
   values=1:5, labels=lab)
#g1 <- g1 + scale_fill_manual(aesthetics="fill", name="Legend A",
#                             values=1:5, labels=lab)
#g1 <- g1 + scale_fill_manual(aesthetics="fill2", name="Legend B",
#                             values=1:5, labels=lab)

print(g1)

Created on 2018-11-30 by the reprex package (v0.2.1)

Legend order is determined by the standard ggplot2 mechanism, see e.g. here:
tidyverse/ggplot2#1353