I am frequently running into this issue and usually after trying multiple variations I give up and just live with the order that ggplot forces onto my plots, but I'm hoping that I can learn how to override this.
library(dplyr)
library(ggplot2)
# Create a demonstration data frame
demoDat <- data.frame(id=seq(1, 6, 1), label=c("john", "bob", "mark", "sue", "jane", "mary"),
measure=c(27, 32, 28, 30, 29, 33), group=factor(rep(c("married", "single"),3)))
# Just confirm that I created what I meant it to
# Create a straight forward plot of my data
ggplot(data=demoDat, aes(y=measure, x=id, group, color=group)) +
# Now I'd like the x-axis to use my labels, and while I don't need to set breaks I do in anticipation of the next desired change
ggplot(data=demoDat, aes(y=measure, x=id, color=group)) +
scale_x_continuous(breaks=demoDat$id, labels=demoDat$label)
# I'd like to display my data in descending order, not ascending (or alphabetical) so I arrange it that way
demoDat <- arrange(demoDat, desc(id))
# But when I plot it, ggplot orders my x-axis in ascending order
ggplot(data=demoDat, aes(y=measure, x=id, color=group)) +
scale_x_continuous(breaks=demoDat$id, labels=demoDat$label)
# What I really want is my x-axis ordered by group so I order my data that way
demoDat <- arrange(demoDat, group)
# And again ggplot ignores the order of my data and just plots it in ascending "id"
ggplot(data=demoDat, aes(y=measure, x=id, color=group)) +
scale_x_continuous(breaks=arrange(demoDat, group)$id, labels=arrange(demoDat, group)$label)
I am aware of the trans="reverse" variable I could send to scale_x_continuous, but that doesn't really solve my problem because I want control over the order of my data.
I've also tried doing an "embedded" arrange within the aes() argument to ggplot to sort the id there, but then the labels don't match; so then I'm sorting all over the place with in the ggplot chain of commands and just begging for errors.
It seems to me in my naiveté that I ought to be able to tell ggplot to just plot the data in the order that I provide it, but i haven't figured out how to do that.
Can anyone explain to me if this is possible and how one goes about it? Or, if there are great reasons why it should not work that way? I'm open to anything that will either help me do what I want to do or convince me that I shouldn't be doing it.
Thanks