本文介绍了ggplotting时,有序数据框的顺序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我经常遇到的问题,我只需要帮助解决此问题即可.我正在尝试使用ggplot绘制排序的数据框.但是,该图的排序方式与我在数据框中的排序方式不同.
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
然后我按my.order对数据框Attribute列进行排序
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
这很好,但是当我尝试用ggplot绘制时,属性再次按字母顺序排序....
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()
请帮助?
推荐答案
您正在寻找 reorder
函数:
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时,有序数据框的顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!