Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered dataframe not same order when ggplotting [duplicate]

Tags:

r

ggplot2

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?

like image 411
jonas Avatar asked Mar 08 '26 15:03

jonas


1 Answers

You're looking for the reorder function:

my.order <- c(4,3,2,1,5)
my.df <- data.frame(Attribute,value,my.order)

ggplot(my.df, aes(x=reorder(Attribute, my.order),y=value)) + 
    geom_point() + 
    coord_flip()

enter image description here

like image 179
Matthew Plourde Avatar answered Mar 11 '26 05:03

Matthew Plourde



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!