2016-09-16 62 views
0

默認情況下ggplot2保持變量不斷出圖中的訂單,例如這裏:a會留在底部,中間b,並c在頂部。GGPLOT2 - barplot移動爲了

enter image description here

我想生產什麼地方根據不斷變化的比例(%)的順序變化的曲線圖。

所以,時間是在y-axisx-axis比例%),就像一個普通barplot。

您可以可視化的表是這樣的:

code color `1` `2` `3` 
1  a red 0.2 0.8 0.2 
2  b blue 0.8 0.0 0.2 
3  c yellow 0.0 0.2 0.6 

我想是這樣的

enter image description here

該地塊按比例現在訂購。這使得能夠更容易地可視化隨着時間的推移狀態之間的層次結構。 (一)blue(二)更爲突出,然後red(一)和最後yellow(三)。情節中的狀態之間的順序可以改變。

但是,我不太清楚該怎麼做。

我嘗試使用orderorder(n)像:

td %>% group_by(time) %>% mutate(ord = order(n, decreasing = T)) 

,並提供明確的位置ggplot

,但它似乎並沒有工作。

t %>% 
    count(time, code) %>% group_by(time) %>% mutate(n = n/sum(n)) %>% 
    ggplot(aes(time, n, fill = code)) + geom_bar(stat = 'identity') + 
    scale_fill_manual(values = c('red', 'blue', 'yellow')) + 
    scale_x_discrete(limits = factor(td$ord)) # positions # 

數據

t = structure(list(id = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 
3L, 4L, 4L, 4L, 5L, 5L, 5L), .Label = c("1", "2", "3", "4", "5" 
), class = "factor"), code = structure(c(2L, 1L, 1L, 2L, 3L, 
3L, 2L, 1L, 3L, 2L, 1L, 3L, 1L, 1L, 2L), .Label = c("a", "b", 
"c"), class = "factor"), time = structure(c(1L, 2L, 3L, 1L, 2L, 
3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), .Label = c("1", "2", 
"3"), class = "factor")), .Names = c("id", "code", "time"), row.names = c(NA, 
-15L), class = "data.frame") 

回答

2

你可以根據n列只是爲了你的data.frame,呼籲ggplot()前:

t %>% 
    count(time, code) %>% group_by(time) %>% mutate(n = n/sum(n)) %>% 
    arrange(desc(n)) %>% # only need to add this line 
    ggplot(aes(time, n, fill = code)) + geom_bar(stat = 'identity') + 
    scale_fill_manual(values = c('red', 'blue', 'yellow')) 

enter image description here