【问题标题】:Sorting a table according to counts [duplicate]根据计数对表格进行排序[重复]
【发布时间】:2019-07-10 00:33:48
【问题描述】:

我想在条形图中显示调查的计数,按国家分类并按性别堆叠。

到目前为止,我能够做的是使用 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

当我将此表输入到条形图函数中时,它不会根据每个国家(列)的观察对条形图进行排序。当我使用 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 教程,了解如何对矩阵进行排序。以这种方式对表格进行排序,也将其转换为向量。

【问题讨论】:

  • 或者如果你可以使用ggplot2(目前更好的解决方案):stackoverflow.com/questions/5208679/…
  • 我想我应该补充说我想使用基本包来做到这一点。
  • 哦,该死的。没错,G. Grothendieck、divibisan 和 Rui Barradas 的上述链接确实很好地解释了这一点。老实说,我用谷歌搜索了很长时间。为什么我没有遇到这个?

标签: r sorting count bar-chart


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-02
    • 2018-12-08
    • 2022-01-11
    • 2021-09-09
    • 2012-06-15
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多