2017-10-06 202 views
0

我有一個數據幀象下面這樣:如何在ggplot中繪製堆積和分組的條形圖?

id month  type count 
___ _______ ______ ______ 
1  1   1  10 
1  1   2  09 
1  1   3  26 
1  2   1  60 
1  2   2  90 
2  2   3  80 
2  1   1  10 
2  1   2  09 
2  1   3  26 
2  2   1  60 
2  2   2  90 
2  2   3  80 
3  1   1  10 
3  1   2  09 
3  1   3  26 
3  2   1  60 
3  2   2  90 
3  2   3  80 

我想以可視化的最佳方式是堆疊組欄像下面的: Stacked and Grouped Bar Chart

所以我

ggplot(df,aes(x=id,y=count,fill=month))+geom_bar(stat="identity",position=position_dodge())+geom_text(aes(label=count),size=3) 
嘗試

這給了一個情節有點不同於我的期望。任何幫助表示讚賞。

回答

1

假設您想將id繪製爲x軸,並排顯示月份並堆疊不同類型,您可以按月分割數據框,併爲每個月添加一個條形圖層,將x移動一定量第二個月吧,使他們可以分開:

barwidth = 0.35 

month_one <- filter(df, month == 1) %>% 
    group_by(id) %>% arrange(-type) %>% 
    mutate(pos = cumsum(count) - count/2) # calculate the position of the label 

month_two <- filter(df, month == 2) %>% 
    group_by(id) %>% arrange(-type) %>% 
    mutate(pos = cumsum(count) - count/2) 

ggplot() + 
    geom_bar(data = month_one, 
      mapping = aes(x = id, y = count, fill = as.factor(type)), 
      stat="identity", 
      position='stack', 
      width = barwidth) + 
    geom_text(data = month_one, 
       aes(x = id, y = pos, label = count)) + 
    geom_bar(data = filter(df, month==2), 
      mapping = aes(x = id + barwidth + 0.01, y = count, fill = as.factor(type)), 
      stat="identity", 
      position='stack' , 
      width = barwidth) + 
    geom_text(data = month_two, 
       aes(x = id + barwidth + 0.01, y = pos, label = count)) + 
    labs(fill = "type") 

給出:

enter image description here


dput(df) 
structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), month = c(1L, 1L, 1L, 2L, 2L, 
2L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), type = c(1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 
3L), count = c(10L, 9L, 26L, 60L, 90L, 80L, 10L, 9L, 26L, 60L, 
90L, 80L, 10L, 9L, 26L, 60L, 90L, 80L)), .Names = c("id", "month", 
"type", "count"), class = "data.frame", row.names = c(NA, -18L 
)) 
+0

非常感謝。所以我們必須把這幾個月分開,然後加入圖表。它的工作方式如何 – Ricky

+0

您已經混合了'堆棧'欄和'閃避'欄。對我而言,如果有一種方法可以自動繪製它,這並不明顯。 – Psidom