Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change order of items in ggplot2 legend with combined items

Tags:

r

ggplot2

I use ggplot2 to draw a scatter plot which contains both a grouped and an ungrouped geom_smooth(). I would like the entry for the ungrouped smooth to appear at the top or bottom of the legend, but the legend is sorted alphabetically instead.

my.colors <- c('4' = 'red', 'f' = 'green', 'r' = 'blue', 'all' = 'black')
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = drv), alpha = 1/3) + theme_bw() +
  geom_smooth(aes(color = drv), method = 'lm') +
  geom_smooth(aes(color = 'all'), method = 'lm') +
  scale_color_manual(name = "Drive Types", values = my.colors)

Scatterplot

The problem is similar to Scott's, but including a geom_blank() does not solve it. Also, including 'all' as a level in mpg$drv makes no difference.

like image 352
severin Avatar asked Dec 02 '25 01:12

severin


1 Answers

Use breaks?

my.colors <- c('4' = 'red', 'f' = 'green', 'r' = 'blue', 'all' = 'black')
ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = drv), alpha = 1/3) + theme_bw() +
  geom_smooth(aes(color = drv), method = 'lm') +
  geom_smooth(aes(color = 'all'), method = 'lm') +
  scale_color_manual(name = "Drive Types", values = my.colors, 
                     breaks=c("all", "4", "f", "r"))
like image 107
KenM Avatar answered Dec 04 '25 14:12

KenM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!