[英]ggplot2, geom_bar, dodge, order of bars
我想在 dodge geom_bar
訂購酒吧。 你知道如何處理嗎?
我的代碼:
ttt <- data.frame(typ=rep(c("main", "boks", "cuk"), 2),
klaster=rep(c("1", "2"), 3),
ile=c(5, 4, 6, 1, 8, 7))
ggplot()+
geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ),
stat="identity", color="black", position="dodge")
和示例圖以更好地理解問題:
我擁有的:
我想要什么:
一種選擇是創建一個新變量來表示條形圖在每個組中的順序,然后將此變量添加為繪圖中的group
參數。
制作變量的任務有很多方法,這里有一種使用dplyr函數的方法。 新變量基於在每個klaster
組內按降序排列ile
。 如果您在任何組中都有關系,您會想弄清楚在這種情況下您想做什么(條形在給定關系中的順序應該是什么?)。 您可能需要設置ties.method
在爭論rank
從默認了,大概是"first"
或"random"
。
library(dplyr)
ttt = ttt %>%
group_by(klaster) %>%
mutate(position = rank(-ile))
ttt
Source: local data frame [6 x 5]
Groups: klaster [2]
typ klaster ile rank position
(fctr) (fctr) (dbl) (dbl) (dbl)
1 main 1 5 3 3
2 boks 2 4 2 2
3 cuk 1 6 2 2
4 main 2 1 3 3
5 boks 1 8 1 1
6 cuk 2 7 1 1
現在只需將group = position
添加到您的繪圖代碼中。
ggplot() +
geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ, group = position),
stat="identity", color="black", position="dodge")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.