I am trying to plot my data using stacked bar plot. I want to put the legend on the top of the plot for aesthetics reasons. However, when I do so the order of the does not match the order of the stacked bars. I tried to change it in a number of different ways but I keep going in a loop switching the order of the bars with the order of the legend. Here is an example similar to my data:
ggplot(diamonds, aes(clarity, fill = cut)) + geom_bar() + coord_flip() +
theme(legend.position = "top", panel.background = element_blank(), axis.line = element_line(colour = "black")) +
scale_y_continuous(name="Count", labels = comma) +
xlab("Clarity") + guides(fill=guide_legend(title="Diamonds Cuts: "))
Then I can order the bars:
levels(diamonds$cut)
[1] "Fair" "Good" "Very Good" "Premium" "Ideal"
diamonds$cut <- factor(diamonds$cut, levels = rev(levels(diamonds$cut)))
levels(diamonds$cut)
[1] "Ideal" "Premium" "Very Good" "Good" "Fair"
And make the plot again:
I would like to match the order of the colors on the legend and the stacked bars. As you can see the both plots has yellow at the left of the bars and at the right of the legend. How can I make it to be in the same order?
Thank you!