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

如何使用ggplot2绘制带百分比格式的字符型变量条形图?

嘿,我来帮你搞定这个带百分比标签的填充条形图!从你给出的代码片段和数据来看,你已经找对了方向,我来帮你补全并优化代码:

步骤1:加载依赖包与数据

首先确保你安装了所需的工具包,然后加载数据:

# 安装包(如果没装过的话)
install.packages(c("ggplot2", "dplyr", "scales"))

# 加载包
library(ggplot2)
library(dplyr)
library(scales)

# 加载你的数据集
load('test.Robj')
步骤2:预处理数据

你的数据里branch列存在NA值,我们可以把它转为一个明确的类别(比如"Unknown"),同时把res.1.2转为因子,这样填充色会按类别区分而非连续色阶:

test_clean <- test %>%
  # 把NA转为"Unknown"类别,保留这部分样本
  mutate(branch = ifelse(is.na(branch), "Unknown", as.character(branch))) %>%
  # 将res.1.2转为因子,确保填充按类别分组
  mutate(res.1.2 = as.factor(res.1.2))
步骤3:绘制带百分比标签的填充条形图

我们先计算每个branch下各res.1.2类别的占比,再用ggplot绘制并添加标签:

# 先计算百分比统计数据
plot_stats <- test_clean %>%
  count(branch, res.1.2) %>%
  group_by(branch) %>%
  mutate(percent = n / sum(n) * 100) %>%
  ungroup()

# 绘制条形图
ggplot(plot_stats, aes(x = branch, y = n, fill = res.1.2)) +
  # 绘制填充条形,position="fill"让每个条形高度为100%
  geom_bar(position = "fill", stat = "identity") +
  # 添加百分比标签,居中显示在每个填充块内
  geom_text(aes(label = sprintf("%.1f%%", percent)),
            position = position_fill(vjust = 0.5),
            size = 3.5) +
  # 将y轴刻度转为百分比格式
  scale_y_continuous(labels = percent_format()) +
  # 设置图表标签
  labs(
    title = "Distribution of res.1.2 by Branch",
    x = "Branch",
    y = "Percentage",
    fill = "res.1.2 Category"
  ) +
  # 用简洁的主题
  theme_minimal()
关键细节说明
  • position="fill":让每个条形的高度统一为1(对应100%),直观展示各类别的占比
  • sprintf("%.1f%%", percent):把百分比格式化为带一位小数的百分比字符串(你可以调整%.1f为%.0f去掉小数)
  • position_fill(vjust=0.5):让标签垂直居中在对应的填充块里
  • 如果不想保留branch为NA的样本,只需要在预处理时加上filter(!is.na(branch))即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:37:36