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

如何将ggplot棒棒糖图的geom_points替换为小饼图展示数据占比

在Tidyverse中用小饼图替换棒棒糖图的点以展示细胞比例

核心思路

要把棒棒糖图的点换成小饼图,关键是先计算每个聚类中各细胞来源的比例,再用ggforce包的geom_arc_bar在棒棒糖的端点绘制扇形(拼成小饼)。全程用Tidyverse管道处理数据,保证代码整洁。

步骤与代码示例

1. 模拟原数据与原棒棒糖图代码

先模拟你可能的原数据结构,原代码大概是这样:

library(tidyverse)

# 模拟原数据:聚类、细胞来源、数量
set.seed(123)
df <- tibble(
  cluster = rep(paste0("Cluster_", 1:5), each = 3),
  source = rep(c("Mouse", "Rat", "Rabbit"), 5),
  count = sample(10:50, 15, replace = TRUE)
)

# 计算每个聚类的总数量(用于棒棒糖图的x轴)
cluster_total <- df %>% 
  group_by(cluster) %>% 
  summarise(total = sum(count)) %>% 
  ungroup()

# 原棒棒糖图代码
original_plot <- df %>% 
  left_join(cluster_total, by = "cluster") %>% 
  ggplot(aes(x = total, y = cluster)) +
  geom_segment(aes(xend = 0, yend = cluster), color = "gray50") +
  geom_point(aes(color = source), size = 5) +
  labs(x = "总细胞数", y = "聚类", color = "细胞来源") +
  theme_minimal()

original_plot

2. 修改为带小饼图的代码

需要先计算每个聚类内各来源的比例和对应的角度范围,再用ggforce::geom_arc_bar绘制小饼:

library(ggforce)

# 数据预处理:计算比例、累积角度
pie_df <- df %>% 
  left_join(cluster_total, by = "cluster") %>% 
  group_by(cluster) %>% 
  mutate(
    prop = count / total,
    start_angle = cumsum(prop) - prop,  # 起始角度(0到1对应0到2π)
    end_angle = cumsum(prop),
    start_angle = start_angle * 2 * pi,  # 转换为弧度
    end_angle = end_angle * 2 * pi
  ) %>% 
  ungroup()

# 绘制带小饼图的棒棒糖图
pie_lollipop_plot <- ggplot() +
  # 先画棒棒糖的线段
  geom_segment(data = cluster_total, 
               aes(x = total, xend = 0, y = cluster, yend = cluster),
               color = "gray50") +
  # 绘制小饼图(用geom_arc_bar,中心在(total, cluster),半径设小)
  geom_arc_bar(data = pie_df,
               aes(x0 = total, y0 = cluster, r0 = 0, r = 0.2,
                   start = start_angle, end = end_angle, fill = source)) +
  labs(x = "总细胞数", y = "聚类", fill = "细胞来源") +
  theme_minimal() +
  # 调整坐标轴,避免小饼被截断
  scale_y_discrete(expand = expansion(add = 0.5))

pie_lollipop_plot

关键说明

  • ggforce::geom_arc_bar需要指定中心坐标(x0, y0)、内半径(r0=0)和外半径(r),这里r设为0.2可以得到合适大小的小饼,你可以根据图的尺寸调整。
  • 角度计算:把比例转换为0到2π的弧度范围,start_angle和end_angle分别对应每个来源扇形的起始和结束弧度。
  • 图层顺序:先画线段,再画小饼,避免小饼被线段遮挡。

适配你的实际数据

如果你的原数据结构不同,只需要调整:

  • 确保cluster列对应聚类名称,source列对应细胞来源,count列对应各来源的细胞数。
  • 调整r的大小,让小饼和整体图协调。

内容的提问来源于stack exchange,提问作者Phil of Fins

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 07:52:05