I am trying to make a bar chart
ggplot(data= Dataa, aes(x = Gender, fill = Q1))
theme_bw()
geom_bar(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"))
I would want to order the bars, for both of the genders, ascending,

CodePudding user response:
One option to achieve your desired result:
- Instead of computing the counts via
geom_baraggregate your data before passing it toggplot - Arrange you data by
Genderand count (which by default is namednbydplyr::count - Group by
Genderand add an helperidor more precisely the rank to eachQ1category. - Map the helper column on the
groupaesthetic 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))
