Change legend order in ggplot when coordinates are flipped

Viewed 45

I have a very simple problem that I did not manage to solve. In the following legend, I would like to have "work" above "sleep" and keep the graph and colors unchanged (so work in blue and sleep in red).

  data <- data.frame(Name = rep(c("Tom","Ana"), 2),
                 Category = rep(c("sleep","work"),each=2),
                 Percentage = c(40,20,60,80))
ggplot(data, aes(fill=Category, y=Percentage, x=Name)) + 
geom_bar(position="fill", stat="identity", colour="black") +
coord_flip()

current graph

Thanks a lot in advance!!!

1 Answers

Nice reprex!

You may need to set the fill colors and levels manually.

library(tidyverse)

data <- data.frame(Name = rep(c("Tom","Ana"), 2),
                   Category = rep(c("sleep","work"),each=2),
                   Percentage = c(40,20,60,80))
ggplot(data, aes(fill=Category, y=Percentage, x=Name)) + 
  geom_bar(position="fill", stat="identity", colour="black") +
  scale_fill_manual(breaks = c("work", "sleep"), values = c("#01BFC4", "#F8766D")) + 
  coord_flip()

Created on 2021-12-07 by the reprex package (v2.0.1)

Related