You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用ggplot2绘制含两组条形的分组条形图:总观测数与达标数

用ggplot2绘制分组条形图:总观测数与薪资达标数对比

首先定义原始数据:

library(tibble)
df <- tibble(
  person = c("Paul", "Paul", "Paul", "Sarah", "Sarah", "Sarah", "Alex", "Alex", "Alex"),
  salary = c(8, 10, 3, 6, 6, 6, 1, 1, 3)
)

步骤1:数据预处理

按人员分组计算所需指标,并转成长格式适配ggplot绘图逻辑:

library(dplyr)
library(tidyr)

summary_df <- df %>%
  group_by(person) %>%
  summarize(
    总观测数 = n(),
    薪资高于5的数量 = sum(salary > 5)
  ) %>%
  pivot_longer(cols = -person, names_to = "指标类型", values_to = "数量")

步骤2:绘制分组并列条形图

通过position_dodge()实现两组条形的并列展示:

library(ggplot2)

ggplot(summary_df, aes(x = person, y = 数量, fill = 指标类型)) +
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  geom_text(aes(label = 数量), 
            position = position_dodge(width = 0.8),
            vjust = -0.5, size = 3.5) + # 添加条形顶部数值标签
  labs(
    title = "各人员薪资观测数对比",
    x = "人员",
    y = "观测数量",
    fill = "指标类型"
  ) +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5)) # 标题居中对齐

效果说明

  • 每个人员对应两个并列条形,分别代表总观测数和薪资高于5的观测数
  • 条形顶部标注具体数值,数据展示更直观
  • 采用极简主题,保证图表清晰易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 21:35:03