Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re-ordering legend in ggplot2

Tags:

r

legend

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

like image 923
J Miller Avatar asked Oct 20 '25 13:10

J Miller


2 Answers

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.

like image 145
camille Avatar answered Oct 23 '25 05:10

camille


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))
like image 22
Carl Avatar answered Oct 23 '25 06:10

Carl



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!