ggplotting [重复]时,有序数据帧的顺序不同

时间:2022-09-14 14:59:00

This question already has an answer here:

这个问题在这里已有答案:

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.

这是我经常遇到的一个问题,我只需要帮助整理这个问题。我正在尝试使用ggplot绘制已排序的数据框。但是,绘图不按照我的数据框中的顺序排序。

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.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绘制它时,属性按字母顺序再次排序....

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

Help please?

请帮助?

1 个解决方案

#1


2  

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()

ggplotting [重复]时,有序数据帧的顺序不同

#1


2  

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()

ggplotting [重复]时,有序数据帧的顺序不同