ggplot2:如何对水平条形图中的类别进行排序?

时间:2017-03-27 15:53:32

标签: r ggplot2

我很难找到在ggplot中重新签名文本x轴的正确方法。 考虑这个简单的例子:

library(ggplot2)
library(dplyr)
dataframe <- data_frame('group' = c(1,1,1,2,2,2),
                        'text' = c('hello', 'world', 'nice', 'hello', 'magic', 'bug'),
                        'count' = c(12,10,3,4,3,2))

> dataframe
# A tibble: 6 × 3
  group  text count
  <dbl> <chr> <dbl>
1     1 hello    12
2     1 world    10
3     1  nice     3
4     2 hello     4
5     2 magic     3
6     2   bug     2

现在是图表

ggplot(dataframe, aes(x = text, y = count, fill = count, group = group)) + 
  geom_bar(stat = 'identity') +
  facet_wrap(~ group,  scales = "free_y") +
  coord_flip() 

enter image description here

问题是:我想按增加count顺序对单词进行排序,以便每个类别的底部显示计数最高的单词。

使用Order Bars in ggplot2 bar graphggplot bar plot with facet-dependent order of categories中的解决方案无济于事。

我怀疑这是与横向水平相关的问题。例如,使用

ggplot(dataframe, aes(x = reorder(text, -count), y = count, fill = count, group = group)) + 
  geom_bar(stat = 'identity') +
  facet_wrap(~ group,  scales = "free_y") +
  coord_flip()

仅排序一个图表(右侧)。

enter image description here

有什么想法吗? 谢谢!

> sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] dplyr_0.5.0   ggplot2_2.2.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.9      digest_0.6.12    assertthat_0.1   grid_3.3.2       plyr_1.8.4      
 [6] R6_2.2.0         gtable_0.2.0     DBI_0.5-1        magrittr_1.5     scales_0.4.1    
[11] lazyeval_0.2.0   labeling_0.3     tools_3.3.2      munsell_0.4.3    colorspace_1.3-2
[16] tibble_1.2   

1 个答案:

答案 0 :(得分:2)

我删除了一些无用的部分,比如小组,使用了'现代化的'<div id="toolbarViewerRight" style="display: none;">...</div> ,但诀窍可能在于每个因子级geom_col()而不是sum,这是默认值mean。始终使用tidyverse函数通常可以避免令人不快的意外,即使reorder也适用于此。

reorder

请记住,因子只有一个顺序,这意味着如果您相应地制作数据,则可以在两个方面进行相反的排序(即每个方面没有排序)。