Reputation: 3
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,
Upvotes: 0
Views: 142
Reputation: 124183
One option to achieve your desired result:
geom_bar
aggregate your data before passing it to ggplot
Gender
and count (which by default is named n
by dplyr::count
Gender
and add an helper id
or more precisely the rank to each Q1
category.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))
Upvotes: 2