ggplot2条形图,带有两个分类变量 [英] ggplot2 bar plot with two categorical variables

查看:230
本文介绍了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.我希望条形图具有苹果和橙子给定的错误计数.所以条形图看起来像这样

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(y = 1的蠕虫(红色),y = 2的蜘蛛(蓝色))BREAK橙色(y = 4的蠕虫(红色),蜘蛛(y = 1的蓝色)

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!

推荐答案

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

这篇关于ggplot2条形图,带有两个分类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆