Search code examples
rggplot2geom-bar

Ggplot Bar chart not fully ordered and wrong count axis scale


I am running into a small glitch with my plot.

I have the following tibble

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)
  )

where the last column, total is the sum of the grouped name.

I have plotted it like this:

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")

and got this plot

plot1

There are two issues with this plot:

  1. The bar for Administrative work is not following in the right order, while all the others are; it should come immediately below Information management.
  2. The scale for the count of the x-axis goes from zero to ten, when it should go from zero to five.

What am I doing wrong?

Many thanks,

Manolo


Solution

    1. By default reorder reorders by the mean in case of multiple values. To get the order right, reorder by the sum.

    2. Map n on x instead of total. Otherwise you get two times total for each group.

    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")
    

    Created on 2021-05-20 by the reprex package (v2.0.0)