I have a stacked bar graph and I'd like to reorder the way the legend appears. I'd like the legend to show the order in "Social", "Economic", and "Environmental", but keep the colors the same. I keep trying different solutions, but I'm a newb and am probably writing the wrong things!
I think I'm on the right track with this, but it's not working:
mortality_df$subsystem <- factor(mortality_df$subsystem, levels = c("Social", "Economic", "Environmental"))
The code without the reordering of the legend:
mortality_df <- results_df %>%
pivot_longer(
cols = starts_with("imp_"),
names_to = "mortality",
names_prefix = "imp_",
values_to = "importance"
) %>%
relocate(c(feature, subsystem, mortality, importance, label))
mortality_df
diabetes_plot <- mortality_df %>%
filter(mortality == "diabetes") %>%
filter(importance > 0) %>%
ggplot(aes(x = reorder(label, importance), y = importance, fill = subsystem)) +
geom_bar(stat = "identity") +
coord_flip() +
scale_y_continuous(name = "Importance Score") +
scale_x_discrete(name = "") +
theme_minimal() +
theme(aspect.ratio = 1.45)
diabetes_plot
Which creates this: