根据计数对表进行排序

时间:2019-02-15 20:25:48

标签: r sorting count bar-chart

我想在一个小图中显示一项调查的计数,按国家分类并按性别分类。

到目前为止,我所能做的就是使用table()函数将答案转换为表格,并按国家/地区将这些答案按频率进行绘制。但是,我无法按性别对计数进行堆叠,而该计数方法无法根据我对每个国家/地区的观察数来对表格进行排序。

我无法创建MWE,所以我将把表格发布到目前为止:

           A    B    C      D     E
  Female   35   7    30     9    11
  Male     30   6     9     7     3
  Other     0   0     1     1     0

当我将此表输入到barplot函数中时,它不会根据每个国家(列)的观察结果对bar图进行排序。当我使用sort函数时,它将表转换为向量。我希望的输出如下所示:

           A    B    C      D     E
  Female   35   30   9     11    7
  Male     30   9     7     3     6
  Other     0   0     1     0     1

因此,最终条形图是按国家/地区总数之和然后按性别排序的。

到目前为止,我还尝试了其他方法:将表转换为矩阵,然后在此处使用this关于如何对矩阵进行排序的教程。以这种方式对表格进行排序,还将其转换为向量。

1 个答案:

答案 0 :(得分:1)

很难理解您到底想要什么,但是我的理解是,您想要一个按性别堆叠的小图,按每个小节的总高度(即来自每个国家/地区的调查参与者的数量)排序。如果正确,这是一个可能的解决方案:

library(ggplot2)
library(dplyr)

# Fake survey data
df <- data.frame(
  country = c(rep("US", 50), rep("UK", 20), rep("CHN", 30)),
  gender = sample(x = c("Female", "Male", "Other"),
                  prob = c(0.49, 0.49, 0.02),
                  size = 100, replace = TRUE)
)
table(df$gender, df$country)
##          CHN UK US
##   Female  12  8 25
##   Male    17 10 25
##   Other    1  2  0

df %>% 
# count the number of survey participants per country, per gender
  count(country, gender, sort = TRUE) %>% 
# Reorder the levels of the factor variable according to the number of survey participants in each country (because the barplot x axis order is determined by the order of the factor levels, which is alphabetical by default)
  mutate(country = forcats::fct_reorder(.f = country, .x = n, .desc = TRUE)) %>% 
# create barplot
  ggplot(aes(x = country, y = n, fill = gender)) +
  geom_col()

enter image description here