簡體   English   中英

如何在ggplot中繪制堆積和分組的條形圖?

[英]How to plot a Stacked and grouped bar chart in 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

我認為可視化的最佳方法是堆疊的組欄,如下所示: 堆疊和分組條形圖

所以我嘗試了

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

給出的情節與我的預期有所不同,我們將不勝感激。

假設您想將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")

給出:

在此處輸入圖片說明


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
))

使用facet_grid可以更徹底地解決此問題:

library(tidyverse)
read_tsv("tmp.tsv", col_types = "ccci") %>%  
ggplot(aes(x=month, y=count, fill=type)) + geom_col() + facet_grid(.~id)

並排堆積的條

請注意,您必須在col_types參數中將前三列指定為“字符”,否則看起來不太好。 最好將數字代碼替換為有意義的內容(例如,將月份變成有序的因子“ January”,“ February”而不是1、2;類型和id類似)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM