Ggplot 条形图未完全排序且计数轴刻度错误

Ggplot Bar chart not fully ordered and wrong count axis scale

我 运行 我的情节出了点小问题。

我有以下小标题

library(tidyverse)
library(RColorBrewer)

tb <- tibble(
  resp_type = c(rep("Case manager", 15), rep("Supervisor", 7)),
  name = c("Administrative work", 
           "Case coordination meetings", 
           "Child protection", 
           "CM guiding principles", 
           "Gender/based violence",
           "Identification of needs and service matching", 
           "Information management", 
           "Informed assent/consent", 
           "Interviewing", 
           "Referral mechanisms", 
           "Report writing",
           "Safeguarding procedures",
           "Social work",
           "Supervision",
           "Survivor involvement",
           "Administrative work",
           "Case coordination meetings",
           "Developing capacities of case managers",
           "Guaranteeing wellbeing of case managers",
           "Information management",
           "Support case managers emotionally",
           "Support difficult cases"),
  n = c(2, 4, 1, 1, 3, 2, 3, 1, 2, 1, 3, 3, 1, 3, 2, 1, 1, 1, 2, 1, 1, 2),
  total = c(3, 5, 1, 1, 3, 2, 4, 1, 2, 1, 3, 3, 1, 3, 2, 3, 5, 1, 2, 4, 1, 2)
  )

其中最后一列 total 是分组 name 的总和。

我是这样画的:

tb %>%
  ggplot(aes(x = total, y = reorder(factor(name), total), fill = resp_type)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  scale_fill_brewer(palette = "Dark2") +
  labs(fill = "Respondent type") +
  ylab(NULL) +
  xlab("Count")

得到了这个情节

这个情节有两个问题:

  1. Administrative work 的柱子顺序不对,而其他柱子都是;它应该紧接在 Information management.
  2. 下方
  3. x-axis 的计数范围从零到十,而它应该从零到五。

我做错了什么?

非常感谢,

马诺洛

  1. 默认情况下 reorder 在多个值的情况下按 mean 重新排序。要获得正确的顺序,请按 sum.

    重新排序
  2. n 映射到 x 而不是 total。否则你会得到每组的两倍。

library(tidyverse)
library(RColorBrewer)

tb %>%
  ggplot(aes(x = n, y = reorder(factor(name), total, sum), fill = resp_type)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  scale_fill_brewer(palette = "Dark2") +
  labs(fill = "Respondent type") +
  ylab(NULL) +
  xlab("Count")

reprex package (v2.0.0)

于 2021-05-20 创建