J Miller
J Miller

Reputation: 89

re-ordering legend in ggplot2

I am trying to re-order my legend in ggplot such that "control" is listed first and than concentration is arranged low-high. I have both put my dataset in the order I would like the legend and tried scale_fill_discrete.

Can you spot any reason this is not working?

p <- ggplot(data = deviation_cloth, aes(x = day, y = Deviation))+
  geom_line(aes(color = factor(Labels)), size = 1)+
  scale_fill_discrete(breaks = c("control", "1E-3","0.01", "0.1", "1", "10"))

p + labs(color = "Conc", x = "Day", y = "Result ")

enter image description here

Upvotes: 4

Views: 11163

Answers (3)

Mike M
Mike M

Reputation: 1425

Just changing the Legend only

Today, it looks like we can also change the Legend order alone by adding a
limits=
declaration to our scale_*_*().

For example,
having set my chosen colors per factor with

scale_fill_manual(
                  values= c(
                        "factor1" = "#64af38", 
                        "factor2" = "#0051e8", 
                        "factor3" = "#cc6389"
                        )
                 )

I can force the legend order to something different,
say factor3 then factor1 then factor2
by simply updating this to

scale_fill_manual(
                  values= c(
                        "factor1" = "#64af38", 
                        "factor2" = "#0051e8", 
                        "factor3" = "#cc6389"
                        ),
                   limits= c(
                        "factor3", 
                        "factor1", 
                        "factor2"
                        )
                  ) 

Upvotes: 0

camille
camille

Reputation: 16881

There's a couple things: comments previously mentioned this, but you mapped Labels to color, but then use a scale function for fill instead. Since it's a line, color makes sense; just change to scale_color_discrete.

Second thing is that you want the limits argument, not the breaks one. Setting limits allows you to define what categories are included and what order they appear in. You can change to scale_color_discrete(limits = c("control", "1E-3","0.01", "0.1", "1", "10"))

Alternatively, you could use an ordered factor and arrange the levels for that variable as you want. fct_relevel from the forcats package, part of the tidyverse, makes it easy to do this without having to give all the levels manually.

Upvotes: 4

Carl
Carl

Reputation: 7540

Maybe this ...

library(tidyverse)

df <-
  data_frame(
    x = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
    y = c(2, 3, 4, 3, 4, 5, 4, 5, 6),
    z = c("a", "a", "a", "b", "b", "b", "c", "c", "c")
  )

ggplot(df, aes(x, y, colour = z)) +
  geom_line()

ggplot(df, aes(x, y, colour = z)) +
  geom_line() +
  guides(colour = guide_legend(reverse = T))

Upvotes: 2

Related Questions