[英]Plot multiple columns with geom_bar()
我最近開始在 R 中編程,我正在嘗試使用 ggplot2 對 plot 幾列進行編程。
我的數據框如下所示:
mydf <- data.frame(Names, Less, Equal, More)
mydf
Names Less Equal More
1 Sarah 8 25 8
2 Mark 13 13 13
3 Peter 11 26 5
為了了解我是如何創建這個數據框的,“Less”看起來像這樣:
[1] 8 13 11
我希望能夠比較每個名字的分數,如果他們的分數更低、相等或更高。 在 x 軸上,我實際上想要 plot “更多”、“更少”和“相等”,每個名稱都有不同的條形。 在 y 軸上,我想打印分數(例如 8、25...)。 我想為每個名稱創建多個欄。
我已經嘗試了幾件事,但我只成功地在 y 軸上添加了一個值:
test <- ggplot(mydf, aes(x= Names, y= More)) +
geom_bar(stat = "identity")
我感覺問題出在我的數據組織方式上,但我不確定。
您需要將數據更改為長格式,其中一列用於值,另一列用於標簽:
Names values label
1 Sarah 8 less
2 Mark 13 less
3 Peter 11 less
1 Sarah 25 equal
2 Mark 13 equal
3 Peter 26 equal
1 Sarah 8 more
2 Mark 13 more
3 Peter 5 more
那么代碼將是
test <- ggplot(mydf, aes(x= label, y= values, fill=names)) +
geom_bar(position="dodge", stat="identity")
test
這是一個例子: https://www.r-graph-gallery.com/48-grouped-barplot-with-ggplot2.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.