ggplot2条形图,带有两个分类变量

时间:2014-07-22 19:00:04

标签: r ggplot2

假设我有以下数据:

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

我想用ggplot创建一个条形图,我们在x轴上有Fruit,填充是bug。我希望条形图有苹果和橙色的错误计数。所以条形图看起来会像这样

Apple(蠕虫(红色),y = 1,蜘蛛(蓝色),y = 2)BREAK橙色(蠕虫(红色),y = 4,蜘蛛(蓝色,y = 1)

我希望这是有道理的。谢谢!

2 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:4)

使用双向表非常容易:

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