假设我有以下数据:

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。我希望条形图具有给定的苹果和橙子的错误计数。所以条形图看起来像这样

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

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

最佳答案

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

关于r - ggplot2条形图,带有两个分类变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24895575/

10-12 23:36