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
There are two issues with this plot:
Administrative work
is not following in the right order, while all the others are; it should come immediately below Information management
.What am I doing wrong?
Many thanks,
Manolo
By default reorder
reorders by the mean
in case of multiple values. To get the order right, reorder by the sum
.
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)