我試圖創建一個條形圖,使用ggplot2一個變量在其中堆疊而另一個變量在其中躲避。這是一個示例數據集:df=data.frame( year=rep(c("2010","2011"),each=4), treatment=rep(c("Impact","Control")), type=rep(c("Phylum1","Phylum2"),each=2), total=sample(1:100,8))我想創建一個條形圖,其中x=treatment,y=total堆疊變量為type和躲避變量為year。我當然可以做一個或另一個:ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity")ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity")但不是兩者!感謝任何可以提供建議的人。
3 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
這是使用構面而不是躲避的另一種選擇:
ggplot(df, aes(x = year, y = total, fill = type)) +
geom_bar(position = "stack", stat = "identity") +
facet_wrap( ~ treatment)
根據泰勒的建議更改: + theme(panel.margin = grid::unit(-1.25, "lines"))

料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
最接近的方法是在dodged條形圖周圍繪制邊框以突出顯示堆積的type值。
ggplot(df, aes(treatment, total, fill = year)) +
geom_bar(stat="identity", position="dodge", color="black")
- 3 回答
- 0 關注
- 882 瀏覽
添加回答
舉報
0/150
提交
取消