[英]ggplot2 bar plot with two categorical variables
假設我有以下數據:
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)
我希望這是有道理的。 謝謝!
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")
使用雙向表非常容易:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.