You need to enable JavaScript to run this app. 使用ggplot2绘制前2大分类下各子分类分组条形图咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用ggplot2绘制前2大分类下各子分类分组条形图咨询

问题背景

现有结构如下的数据集:

CategorySubCategoryidStatePopulation
Achair1CA100
Adesk2CA150
Achair3NY80
Efan4AZ60
Eac5PA55
Bchair6PA78
Efan7PA90
Btable8PA120
Abed9UT105
Achair10NY156
Adesk11NY99

对应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)
需求说明
  1. 按category对应的id出现次数,筛选排名前2的category(即A、E)
  2. 统计这2个category下所有subcategory对应的id计数
  3. 使用ggplot2绘制分组条形图,y轴为id的计数
实现代码

首先加载所需依赖包:

library(dplyr)
library(ggplot2)

第一步:筛选出id出现次数Top2的category

# 统计每个category的id数量,取前2名
top2_category <- df %>% 
  count(category, sort = TRUE) %>% 
  slice(1:2) %>% 
  pull(category)

第二步:生成绘图所需数据集,统计目标category下所有subcategory的id计数

plot_data <- df %>% 
  # 仅保留前2名的category数据
  filter(category %in% top2_category) %>% 
  # 按category和subcategory分组统计id数量
  count(category, subcategory, name = "id_count")

第三步:绘制分组条形图

ggplot(plot_data, aes(x = category, y = id_count, fill = subcategory)) +
  # position_dodge实现分组展示
  geom_col(position = position_dodge(width = 0.9), width = 0.7) +
  labs(
    x = "大类",
    y = "id计数",
    fill = "子类"
  ) +
  theme_bw()

如果需要以subcategory为x轴、category为分组维度,修改aes映射即可:

ggplot(plot_data, aes(x = subcategory, y = id_count, fill = category)) +
  geom_col(position = position_dodge(width = 0.9), width = 0.7) +
  labs(
    x = "子类",
    y = "id计数",
    fill = "大类"
  ) +
  theme_bw()

内容的提问来源于stack exchange,提问作者hk2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 09:54:01