Reorder items in ggplot2 legend with combined items

I am using ggplot2

to draw a scatter plot that contains both grouped and non-grouped geom_smooth()

. I would like the entry for 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 it geom_blank()

doesn't solve the problem. Also, the inclusion 'all'

as a level in mpg$drv

does not matter.

+3


source to share


1 answer


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"))

      

+4


source







All Articles