I am working on a bar graph that shows counts of cats and dogs that differ across countries. Cats and dogs are levels stored in different factors/ variables. I want to plot the bars for each animal count on top of the other (i.e. 2 layers), and then I want to order the bars from the tallest (i.e. highest count) to lowest according to animal frequency per country.
Here is what I did:
Order the data table according to animal counts per country
plot <- within(plot, country <- factor(country, levels=names(sort(table(country), decreasing=TRUE))))
Plot the graph
gg <- ggplot(data = plot, aes(x=country))
Add bar for dogs
dogs <- gg + geom_bar(data = plot[plot$animal1 == 'dog',], #select dogs from animal1 variable stat="count")
If I do that, I get this (with one geom_bar
):
So far, so good. Next, I add the second geom_bar for the cats:
dogs_cats <- gg +
geom_bar(data = plot[plot$animal1 == 'dog',], #select dogs from animal1 variable
stat="count") +
geom_bar(data = plot[plot$animal2 == 'cat',], #select cats from animal2 variable
stat="count")
Now the order is changed and off-key (after the second geom_bar
):
How can I maintain the order of the bars to follow the initial geom_bar
?
Many thanks!