R 带有两个分类变量的ggplot2条形图
假设我有以下数据:R 带有两个分类变量的ggplot2条形图,r,ggplot2,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 O
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
FruitFruit这是一个非常简单的双向表格:
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")
你试过了吗ggplot(df,aes(x=Fruit))+geom_bar(aes(fill=Bug))
您是否进一步查看了这里的示例,ggplot2
实际上有一个选项,可以直接使用.count..
和.density..
绘制计数/密度,而不是使用双向表。count
的值在哪里?@SabreWolfy我通过列出数据data.frame(表(df$Fruit,df$Bug))
,,您还可以使用内置函数,如@tkmckenzie所说。
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")