14

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!

theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72

2 Answers2

35
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

tkmckenzie
  • 1,353
  • 1
  • 10
  • 19
9

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

bjoseph
  • 2,116
  • 17
  • 24
  • 1
    Further, `ggplot2` actually has an option to plots counts/densities with `..count..` and `..density..` directly rather than using a two-way table. – tkmckenzie Jul 22 '14 at 19:23
  • 1
    Where is the value for `Count`? – SabreWolfy Apr 18 '16 at 12:28
  • @SabreWolfy I generate it by tabling the data `data.frame(table(df$Fruit,df$Bug))`, you can also use the built in functions like @tkmckenzie says. – bjoseph Apr 18 '16 at 14:27