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

如何用ggplot2创建华夫饼图展示两组True/False值分布?

用ggplot2绘制True/False分布的华夫饼图

没问题!要实现你说的两个分组的华夫饼图(上方80样本含3个True,下方280样本含2个True),我给你两种实用方法,你可以按需选择:

方法一:纯ggplot2构造(无需额外包)

这种方法能让你完全掌控每个元素的细节,适合想深入理解原理的情况:

步骤1:构造方块数据

首先我们要为每个样本生成对应的坐标点,每个点代表一个方块:

library(ggplot2)

# 构造第一组(80样本)的方块数据:10列×8行=80个方块
group1_df <- data.frame(
  x = rep(1:10, 8),          # x轴坐标(10列)
  y = rep(8:1, each = 10),   # y轴坐标(8行,倒序让第一行在上方)
  category = c(rep("True", 3), rep("False", 77)),  # 标记True/False
  group = "Group 1 (80 samples)"
)

# 构造第二组(280样本)的方块数据:20列×14行=280个方块
group2_df <- data.frame(
  x = rep(1:20, 14),
  y = rep(14:1, each = 20),
  category = c(rep("True", 2), rep("False", 278)),
  group = "Group 2 (280 samples)"
)

# 合并两组数据
all_df <- rbind(group1_df, group2_df)

步骤2:绘制华夫饼图

用geom_tile绘制方块,配合分面实现上下排列:

ggplot(all_df, aes(x = x, y = y, fill = category)) +
  # 绘制方块,白色边框区分每个样本
  geom_tile(color = "white", size = 0.5) +
  # 垂直分面,每个分组占一行
  facet_wrap(~group, ncol = 1, scales = "free") +
  # 自定义颜色:True用显眼的绿色,False用灰色突出对比
  scale_fill_manual(values = c("True" = "#2ecc71", "False" = "#bdc3c7")) +
  # 简化主题,去掉冗余元素
  theme_minimal() +
  theme(
    axis.text = element_blank(),        # 隐藏坐标轴文字
    axis.title = element_blank(),      # 隐藏坐标轴标题
    panel.grid = element_blank(),      # 隐藏网格线
    legend.position = "bottom",        # 图例放在底部
    strip.text = element_text(size = 12, face = "bold")  # 分组标题加粗
  ) +
  labs(fill = "Value")  # 设置图例标题

方法二:用waffle包简化操作

如果你想快速实现,waffle包专门用来做华夫饼图,代码更简洁:

步骤1:安装并加载包

install.packages("waffle")
library(waffle)

步骤2:绘制分组华夫饼图

直接传入每组的True/False数量,设置行数让两个图高度更协调:

# 定义每组的数量
waffle_data <- list(
  "Group 1 (80 samples)" = c(True = 3, False = 77),
  "Group 2 (280 samples)" = c(True = 2, False = 278)
)

# 绘制华夫饼图
waffle(waffle_data, 
       rows = c(8, 14),  # 第一组8行(80个方块),第二组14行(280个方块)
       colors = c("#2ecc71", "#bdc3c7"),  # 同方法一的颜色
       legend_pos = "bottom") +
  theme(strip.text = element_text(size = 12, face = "bold"))

两种方法都能得到清晰的华夫饼图,直观展示两组样本中True值的稀疏分布~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:25:10