ggplot2:排序一个情节

Bra*_*sen 55 r ggplot2

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

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() 
Run Code Online (Sandbox Code Playgroud)

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

小智 76

这似乎是你正在寻找的:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()
Run Code Online (Sandbox Code Playgroud)

reorder()功能将根据重新排序x轴的项目valuevariable.

  • 最好添加一个关于这应该做什么的解释. (9认同)
  • 如果有人遇到`formatter =`参数的问题:在最近的版本中,这已经变为`labels = scales :: percent`(参见http://stackoverflow.com/a/14511974/2761742). (2认同)

Gre*_*now 61

这有几种方法.

第一个将根据数据框中看到的顺序排序:

x$variable <- factor(x$variable, levels=unique(as.character(x$variable)) )
Run Code Online (Sandbox Code Playgroud)

第二个基于另一个变量(在这种情况下为值)对级别进行排序:

x <- transform(x, variable=reorder(variable, -value) ) 
Run Code Online (Sandbox Code Playgroud)

  • 我希望ggplot2会被重写,以使它更容易.我已经对data.frame进行了排序,以及为什么订单不受图表的尊重.... (4认同)

Mat*_*eoS 9

我最近一直在努力解决相关问题,详细讨论了这个问题:ggplot2条形图中带有coord_flip()的图例条目顺序.

事实上,我很难清楚地解释我的问题,涉及因素和coord_flip()之间的关系,就像这里的情况一样.

我通过添加+ xlim(rev(levels(x$variable)))到ggplot语句得到了所需的结果:

ggplot(x, aes(x=variable,y=value)) + geom_bar() + 
scale_y_continuous("",formatter="percent") + coord_flip() 
+  xlim(rev(levels(x$variable)))
Run Code Online (Sandbox Code Playgroud)

这颠倒了x轴中原始数据框中的因子顺序,它将成为带有coord_flip()的y轴.请注意,在此特定示例中,变量也恰好按字母顺序排列,但指定其中的任意级别顺序xlim()通常应该起作用.


Nel*_*Gon 5

我不知道为什么这个问题被重新提出,但这是一个tidyverse选项。

x %>% 
  arrange(desc(value)) %>%
  mutate(variable=fct_reorder(variable,value)) %>% 
ggplot(aes(variable,value,fill=variable)) + geom_bar(stat="identity") + 
  scale_y_continuous("",label=scales::percent) + coord_flip() 
Run Code Online (Sandbox Code Playgroud)