Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 bar plot with two categorical variables

Tags:

r

ggplot2

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!

like image 465
theamateurdataanalyst Avatar asked Jul 22 '14 19:07

theamateurdataanalyst


2 Answers

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

like image 90
tkmckenzie Avatar answered Sep 21 '22 06:09

tkmckenzie


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

like image 40
bjoseph Avatar answered Sep 21 '22 06:09

bjoseph