简体   繁体   中英

Move order of legend entries of same aesthetic but different data in ggplot

I have a little different data, but this here should make the point:

x = seq(1, 10, 0.1)
y = x + rnorm(10)
df = data.frame(x = x, y = y)
sample = sample(c(TRUE, FALSE),
                nrow(df),
                replace = T,
                prob = c(.7, .3))
train = df[sample,]
test = df[!sample,]

Plotting the data, plus a quantile regression for the 50 % quantile I do this way:

ggplot(train, aes(x, y)) +
  geom_point(aes(color = "train")) +
  geom_point(data = test,
             aes(color = "test")) +
  geom_quantile(quantiles = 0.05,
                aes(color = "median regression"))

Which gives this plot:

在此处输入图像描述

Now let's say that I would like to have my legend in the order:

  • test
  • median regression
  • train

How could I do that?

you can add a vector to the color palette, with names in order as you want:

ggplot(train, aes(x, y)) +
  geom_point(aes(color = "train")) +
  geom_point(data = test,
             aes(color = "test")) +
  geom_quantile(quantiles = 0.05,
                aes(color = "median regression"))+
  scale_color_discrete(limits = c("test", "median regression", "train"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM