Reordering the bars from low to high

Solution 1:

One option to achieve your desired result:

  1. Instead of computing the counts via geom_bar aggregate your data before passing it to ggplot
  2. Arrange you data by Gender and count (which by default is named n by dplyr::count
  3. Group by Gender and add an helper id or more precisely the rank to each Q1 category.
  4. Map the helper column on the group aesthetic so that the bars are ordered according to rank.

Besides that we have to switch to geom_col and map the manually calculated counts on the y aesthetic.

Using some fake random example data:

library(ggplot2)
library(dplyr)

# Aggregate data, arrange and add helper variable
Dataa1 <- Dataa %>% 
  count(Gender, Q1) %>% 
  arrange(Gender, n) %>%
  group_by(Gender) %>% 
  mutate(id = row_number())

ggplot(data= Dataa1, aes(x = Gender, y = n, group = id, fill = Q1)) +
  theme_bw() + 
  geom_col(position = "dodge") +
  labs(title = "Figure 1.1", subtitle = "Distribution of national exam scores by region", y = "Count", x = "Average score for each student (MSTUDENT)") +
  theme(plot.subtitle=element_text(face="bold")) +
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(),   
        panel.background = element_blank(), axis.line = element_line(colour = "black"))+
  theme(plot.title=element_text(face="bold"))

DATA

set.seed(123)

Dataa <- data.frame(
  Gender = rep(c("Kvinner", "Mann"), 100),
  Q1 = sample(paste0("Bank", 1:10), 200, replace = TRUE)
)
Dataa$Q1 <- factor(Dataa$Q1, levels = paste0("Bank", 1:10))