This question already has an answer here:
- Change the order of a discrete x scale 5 answers
- ggplot2: change order of display of a factor variable on an axis 2 answers
This is a problem I run into frequently, and I just need help sorting this issue out. I'm trying to plot a sorted dataframe with ggplot. However, the plot is not ordered the way it is ordered in my dataframe.
Simple example to illustrate my problem:
value <- c(5,8,9,11,3)
Attribute <- c("a", "b", "c","d","e")
my.order <- as.factor(c(4,3,2,1,5))
my.df <- data.frame(Attribute,value,my.order)
my.df
# Attribute value my.order
#1 a 5 4
#2 b 8 3
#3 c 9 2
#4 d 11 1
#5 e 3 5
Then I order the dataframe , Attribute column by my.order
my.df.ordered <- my.df[with(my.df, order(my.order, Attribute)), ]
my.df.ordered
# Attribute value my.order
#4 d 11 1
#3 c 9 2
#2 b 8 3
#1 a 5 4
#5 e 3 5
This is all fine, but when I try to plot this with ggplot, the Attributes are ordered alphabetically again....
ggplot(my.df.ordered, aes(x=Attribute,y=value))+ geom_point()+ coord_flip()
Help please?