8
votes

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!

2
Have you even tried? ggplot(df, aes(x = Fruit)) + geom_bar(aes(fill = Bug))David Arenburg
Have you looked at the examples here docs.ggplot2.org/0.9.3.1/geom_bar.htmlkonvas

2 Answers

26
votes
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")

enter image description here

5
votes

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")

enter image description here