0

I would like to plot male and female side by side for each age range in a stacked bar chart in r. Unfortunately, I get two separate parts, one for male and a second for female. How can I put male and female together for each age range? Apart from that, the legend for "gender" is wrong. How can I change it too? My dataframe looks like this:

enter image description here

#create age ranges
age_ranges <- cut(df_final$age, breaks=c(25,34,44,54,65))

#group data by age range, gender, and education level, and calculate mean value
earnings_data <- aggregate(df_final$earnings, by=list(age_ranges, df_final$gender, df_final$education), FUN=mean)

#calculate the percentage of each education level for each age range and gender group
earnings_data <- earnings_data %>%
  group_by(Group.1, Group.2) %>%
  mutate(share = x/sum(x)*100)

#specify colors for each education level
colors <- c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c", "#FF0000", "#00FF00", "#0000FF", "#FFFF00")

#create plot with facets and text labels for education share
ggplot(earnings_data, aes(x=Group.1, y=x, fill=interaction(Group.3))) + 
  geom_bar(stat="identity", position="stack") +
  labs(title="Mean Earnings by Age Range and Gender", x="Age Range", y="Mean Earnings") +
  facet_grid(. ~ Group.2, scales="free_x", space="free_x") +
  scale_fill_manual(values=colors, name="Gender") +
  geom_text(aes(label=paste(round(share,1), "%"), color=as.factor(Group.3)), position=position_stack(vjust=0.5), size=3.5) +
  scale_color_manual(values=colors, name="Education Level") +
  guides(fill=guide_legend(reverse=TRUE))

enter image description here

TFT
  • 129
  • 10
  • 2
    Just swap your x and faceting variables - in other words plot Mean Earnings against Gender (defined by Group.2?) and then facet by Age Range. – Paul Stafford Allen Apr 14 '23 at 11:14

0 Answers0