2015-10-14 73 views
4

我想在道奇geom_bar中訂購酒吧。你知道如何處理它嗎? 我的代碼:ggplot2,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") 

而且例如地塊,以更好地理解這個問題:

What I have

What I would like to have

+0

瑪塔您好,歡迎計算器! – maj

回答

5

一種選擇是做一個新的變量來表示吧應該順序在每個組內,然後將這個變量作爲group參數添加到您的圖中。

很多方法來完成這個變量的任務,這裏有一個使用dplyr中的函數的方法。新變量基於每個klaster組中排名ile的降序排列。如果你在任何一個組中都有聯繫,那麼你就需要弄清楚在這種情況下你想要做什麼(聯繫中的酒吧應該遵循什麼順序?)。您可能需要將rank中的ties.method參數設置爲遠離默認值,可能爲"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") 

enter image description here

+0

通常它有效 - 有一個例外。當兩根酒吧有相同的高度。像這裏:'ttt < - data.frame(typ = rep(c(「main」,「boks」,「cuk」),2),klaster = rep(c(「1」,「2」),3) ,ile = c(5,4,6,7,8,7))。你知道如何解決這種情況嗎? – Marta

+1

@Marta取決於按照什麼順序排列條紋,但考慮到答案可以將'rank'中的'ties.method'參數設置爲遠離默認的''average''到其他選項之一。有關更多信息,請參閱「排名」幫助頁面。 – aosmith