Suppose I have the following data:
Fruit <- c(rep("Apple",3),rep("Orange",5))
Bug <- c("worm","spider","spider","worm","worm","worm","worm","spider")
df <- data.frame(Fruit,Bug)
df
Fruit Bug
1 Apple worm
2 Apple spider
3 Apple spider
4 Orange worm
5 Orange worm
6 Orange worm
7 Orange worm
8 Orange spider
I want to use ggplot to create a bar graph where we have Fruit on x axis and the fill is the bug. I want the bar plot to have counts of the bug given apple and orange. So the bar plot would look would be like this
Apple (worm(red) with y = 1,spider(blue) with y = 2) BREAK Orange(worm(red) with y = 4, spider(blue with y = 1)
I hope that makes sense. Thanks!
Fruit <- c(rep("Apple",3),rep("Orange",5))
Bug <- c("worm","spider","spider","worm","worm","worm","worm","spider")
df <- data.frame(Fruit,Bug)
ggplot(df, aes(Fruit, ..count..)) + geom_bar(aes(fill = Bug), position = "dodge")
This is pretty easy to do with a two way table:
dat <- data.frame(table(df$Fruit,df$Bug))
names(dat) <- c("Fruit","Bug","Count")
ggplot(data=dat, aes(x=Fruit, y=Count, fill=Bug)) + geom_bar(stat="identity")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With