I have data frame like dat, and I wanted to graph region-wise grouped bar plots in a way that each region is ordered from low to high. I have checked other similar questions but I couldn’t find a solution to my problem. Would appreciate if someone could advise me how to handle it.
dat <- tribble(
~Country, ~Region, ~var,
"Jordan", "MENA", 42,
"Iran", "MENA", 26,
"Turkey", "ECA", 37,
"Pakistan", "AP", 42,
"Indonesia", "AP", 84,
"Bangladesh", "AP", 24,
"Israel", "MENA", 65
)
dat %>%
mutate(across(.cols = Region, .fns = ~readr::parse_factor(.x,
levels = c("AP", "ECA", "MENA"),
ordered = TRUE))) %>%
ggplot(aes(x = as.factor(Country), y = var, fill = Region)) +
geom_bar(stat="identity", position = "dodge")
>Solution :
You could order the factor within your region based on the levels order of your factor like this:
library(tidyverse)
dat %>%
mutate(across(.cols = Region, .fns = ~readr::parse_factor(.x,
levels = c("AP", "ECA", "MENA"),
ordered = TRUE))) %>%
ggplot(aes(x = factor(Country, levels = unique(Country[order(Region, var)]), ordered = TRUE), y = var, fill = Region)) +
geom_bar(stat="identity", position = "dodge")

Created on 2023-06-26 with reprex v2.0.2
