【问题标题】:Ggplot Bar chart not fully ordered and wrong count axis scaleGgplot条形图未完全排序且计数轴刻度错误
【发布时间】:2021-08-09 13:27:57
【问题描述】:

我的情节遇到了一个小故障。

我有以下小标题

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. x 轴计数的刻度从零到十,而应该从零到五。

我做错了什么?

非常感谢,

马诺洛

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:
    1. 默认情况下,reordermean 重新排序,以防有多个值。要正确订购,请通过 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 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      • 2018-02-09
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多