ggplot2:对绘图进行排序 [英] ggplot2: sorting a plot

查看:44
本文介绍了ggplot2:对绘图进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame,从高到低排序.例如:

I have a data.frame, that is sorted from highest to lowest. For example:

x <- structure(list(variable = structure(c(10L, 6L, 3L, 4L, 2L, 8L, 
9L, 5L, 1L, 7L), .Label = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j"), class = c("ordered", "factor")), value = c(0.990683229813665, 
0.975155279503106, 0.928571428571429, 0.807453416149068, 0.717391304347826, 
0.388198757763975, 0.357142857142857, 0.201863354037267, 0.173913043478261, 
0.0496894409937888)), .Names = c("variable", "value"), row.names = c(10L, 
6L, 3L, 4L, 2L, 8L, 9L, 5L, 1L, 7L), class = "data.frame")

ggplot(x, aes(x=variable,y=value)) + geom_bar(stat="identity") + 
 scale_y_continuous("",label=scales::percent) + coord_flip() 

现在,数据很好并且已经排序,但是当我绘图时,它会按因子排序.很烦人,我该如何解决?

Now, the data is nice and sorted, but when I plot, it comes out sorted by factor. It's annoying, how do I fix it?

推荐答案

这里有几种方法.

第一个将根据在数据框中看到的顺序对事物进行排序:

The first will order things based on the order seen in the data frame:

x$variable <- factor(x$variable, levels=unique(as.character(x$variable)) )

第二个根据另一个变量(本例中的值)对级别进行排序:

The second orders the levels based on another variable (value in this case):

x <- transform(x, variable=reorder(variable, -value) ) 

这篇关于ggplot2:对绘图进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆