Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 ignores order of colors in scale_color_manual()

Tags:

r

ggplot2

I have some code which was previously working, but now it isn't anymore. Earlier, values in scale_xy_manual() functions determined the order of the legend items. But now it is not anymore.

Here is an example:

ggplot() +
  geom_line(aes(x = 1:10, y = 1:10, col = "b")) +
  geom_line(aes(x = 1:10, y = (1:10)*0.5, col = "a")) +
  scale_color_manual(values = c("b" = "blue", "a" = "red"), labels = c("b", "a"))

I would expect the line with the lower slope to be red and the other line to be blue. And the labels to be ordered "b" and then "a". However, this is my output:

enter image description here

ggplot2 apparently ignores the order of the values string for the legend. The lines have the right colors, the order of the labels in the legend is right, but the legend does not match the used colors. How can I fix this?

like image 424
Zoe Avatar asked Dec 17 '25 12:12

Zoe


1 Answers

The labels argument just creates new labels, overwriting the labels in the legend. By default, this will follow the alphabetical ordering "a", "b". So all you are doing is writing over "a" with "b" and "b" with "a".

If you want to change the ordering of labels, you can specify the order using breaks. You don't need labels at all unless you want to actually change the text of the printed labels.

ggplot() +
  geom_line(aes(x = 1:10, y = 1:10, col = "b")) +
  geom_line(aes(x = 1:10, y = (1:10)*0.5, col = "a")) +
  scale_color_manual(values = c("b" = "blue", "a" = "red"), 
                     breaks = c('b', 'a'))

enter image description here

like image 175
Allan Cameron Avatar answered Dec 19 '25 05:12

Allan Cameron