I stumbled onto this weird behavior with ggplot2s ordering of legends and just can't figure out what the logic behind the automatic placement of the legends is:
My aim: In a plot with multiple scales I want to arrange them in a different (thematic) order than the automatic one. But I couldn't find a command in opts() or guides() to do this for me. And just to be clear: I don't want to change the items within the legends, that works fine, but the arrangement of multiple complete legends.
So first I assumed they were ordered by type, i.e. scale, colour etc. But that is not the case, their position changes (see below).
Alphabetical order? No.
library(ggplot2) ## v0.9
## Scale_colour on top
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "A") + scale_colour_discrete(name = "B")
## Reverse names --> scale_colour on bottom
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "B") + scale_colour_discrete(name = "A")
## Change name B to C --> scale_colour on bottom
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "C") + scale_colour_discrete(name = "A")
## Change name B to D --> scale_colour on top
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class) +
scale_size(name = "D") + scale_colour_discrete(name = "A")
Further positions of scale_colour (for exchanged scale_size name)
- "E": bottom
- "F" - "L": top
- "M" - "N": bottom
and it continues to appear on top an at the bottom.
Factorial order? No.
## From top to bottom: C - B - A
fname <- factor(c("A","B","C"), levels = c("A","B","C"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl) +
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
## From top to bottom: B - C - A
fname <- factor(c("A","B","C"), levels = c("C","B","A"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl) +
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
## From top to bottom: B - C - A
fname <- factor(c("A","B","C"), levels = c("B","C","A"))
qplot(data = mpg,x = displ, y = cty, size = hwy, colour = class, alpha = cyl)+
scale_size(name = fname[1]) + scale_colour_discrete(name = fname[2]) + scale_alpha(name=fname[3])
Length of title? No. I'll stop for now with example code, but that one also yielded fluctuating orders independent of character length.
Any ideas?
scale_size(name = " B") + scale_colour_discrete(name = " C")
). That method, though, again fails when there are more than two legends to be arranged... – Josh O'Brienhash
of them, so there is no way to predict the order... Definitely this is bad idea of my implementation. I (or Hadley or WCH) will fix this problem in the future version. – kohske