Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply ascending order within groups in bar plots

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading