3

I have a a line graph and I want to reorder the way in which the factors appear in the legend. I have tried scale_fill_discrete but it doesn't change the order. Here's a simulation of my problem:

df <- data.frame(var1=c("F", "F", "F", "B", "B", "B"),
                 var2=c("levelB", "levelC", "levelA"),
                 value=c("2.487585", "2.535944", "3.444764", "2.917308", "2.954155","3.739049"))

p <- ggplot(data=df, aes(x=var1, y=value, 
  group=var2, colour=var2, shape = var2)) +
  geom_line(size = 0.8) +
  geom_point()+
  xlab("var1") + ylab("Value") +
  scale_x_discrete(limits=c("F","B")) + 
  theme(legend.title = element_text(size=12)) + 
  theme(legend.text = element_text(size=10)) +
  scale_fill_discrete(breaks=c("levelB","levelC","levelA")) +
  theme(title = element_text(size=12)) +
  blank + scale_color_manual(values=c("green2", "red", "black")) +
  theme(legend.key = element_blank())
p

Which creates this:

enter image description here

I would like everything to remain the exactly the same, except for the legend, where I would like to change the order to levelB then levelC then levelA. I'm guessing ggplot2 orders the legend alphabetically and I would like to override this. Reordering my data frame didn't work, and scale_fill_discrete also doesn't change it. Any ideas?

Thanks!

Daniel Langdon
  • 5,899
  • 4
  • 28
  • 48
pd441
  • 2,644
  • 9
  • 30
  • 41
  • 1
    Possible duplicate of [Controlling ggplot2 legend display order](http://stackoverflow.com/questions/11393123/controlling-ggplot2-legend-display-order) – jeremycg Nov 02 '15 at 14:39
  • 3
    Not a duplicate as that question deals with the ordering of multiple legends, instead of ordering inside the legend. – kneijenhuijs Nov 02 '15 at 14:42

1 Answers1

13

By reordering the levels in your factor, you can change the order of the legend labels. Run:

df$var2 <- factor(df$var2, levels=c("levelB", "levelC", "levelA"))

Then rerun the ggplot code, and levelB should now be at the top of the legend and green, levelC second and red, and levelA third and black.

kneijenhuijs
  • 1,189
  • 1
  • 12
  • 21
  • 1
    Thanks, Yes that worked. It only additionally requires to reorder to colors as so: scale_color_manual(values=c("black", "red", "green2")) + – pd441 Nov 02 '15 at 14:58
  • Oh, I missed that you wanted everything else to stay the same (so also the colors)! Yes, that would require the reordering of the colours then. – kneijenhuijs Nov 02 '15 at 15:00