簡體   English   中英

Plot 分組條 plot 用於前 2 個類別中的每個子類別,使用 ggplot2

[英]Plot grouped bar plot for each subcategory within top 2 categories using ggplot2

我有一個與下面給出的示例數據集非常相似的數據集:

| Category | SubCategory | id | State | Population |
|----------|-------------|----|-------|------------|
| A        | chair       | 1  | CA    | 100        |
| A        | desk        | 2  | CA    | 150        |
| A        | chair       | 3  | NY    | 80         |
| E        | fan         | 4  | AZ    | 60         |
| E        | ac          | 5  | PA    | 55         |
| B        | chair       | 6  | PA    | 78         |
| E        | fan         | 7  | PA    | 90         |
| B        | table       | 8  | PA    | 120        |
| A        | bed         | 9  | UT    | 105        |
| A        | chair       | 10 | NY    | 156        |
| A        | desk        | 11 | NY    | 99         |

下面是 dataframe:

category= c("A","A","A","E","E","B","E","B","A","A","A")
subcategory = c("chair","desk","chair","fan","ac","chair","fan","table","bed","chair","desk")
id = c(1,2,3,4,5,6,7,8,9,10,11)
population = c(100,150,80,60,55,78,90,120,105,156,99)
df= data.frame(category, subcategory, id, population, stringsAsFactors = T)

如果我們查看表格,每個類別 A、B 和 E 的“id”列的總數為 6,2,3(基本上每個類別的出現)。 現在,我一直想要 plot 一個分組條 plot 使用 ggplot2 為屬於前 2 個類別的每個子類別(列第 2 列)確定。 因此,我的 output 應該只顯示類別 A 和 E,並且列 id 的計數應該針對屬於每個子類別的 y 軸繪制(如下所示): 在此處輸入圖像描述

我的代碼塊是根據每個類別的 id 計數為我提供前 2 個子類別,而我正在尋找 plot 基於前 2 個類別的 id 計數的所有子類別。


df %>% add_count(category, name = 'rank') %>%
  filter(dense_rank(desc(rank)) %in% 1:2) %>%
  count(category, subcategory) %>%
  ggplot(aes(x = category, y = n, fill = subcategory)) +
  geom_col(position = 'dodge') +
  geom_text(aes(label = n), position = position_dodge(1), vjust = 1)

在此處輸入圖像描述

暫無
暫無

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

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