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

如何在R语言ggseqplot的堆叠图中添加计数标签

为ggseqplot的堆叠序列图添加计数标签

要给ggseqdplot生成的堆叠序列图每个路径(堆叠)添加样本计数标签,可通过提取绘图数据并叠加文本层实现,具体步骤如下:

1. 准备示例数据

data(biofam)
biofam <- biofam[sample(nrow(biofam),300),]
biofam.lab <- c("Parent", "Left", "Married", "Left+Marr",
                "Child", "Left+Child", "Left+Marr+Child", "Divorced")
biofam.seq <- seqdef(biofam, 10:25, labels=biofam.lab)

2. 生成基础绘图并添加计数标签

# 创建基础序列堆叠图
p <- ggseqdplot(biofam.seq, border = T) +
  scale_fill_discrete_sequential("PuBuGn")+ 
  scale_x_discrete() +
  labs(x = "Path Number") +
  theme(legend.position = "right") +
  theme_minimal()

# 提取绘图底层数据,计算每个路径的总比例与实际样本计数
plot_data <- ggplot_build(p)$data[[1]]
path_stats <- aggregate(y ~ x, data = plot_data, FUN = sum)
path_stats$count <- round(path_stats$y * nrow(biofam.seq))  # 转换为实际样本数

# 叠加计数标签到每个堆叠顶部
p + geom_text(data = path_stats, aes(x = x, y = y, label = count),
              vjust = -0.5, size = 3.5)

说明

  • ggplot_build(p)$data[[1]]提取了堆叠图的底层数据,其中y代表每个路径的相对比例,x对应路径编号。
  • 通过aggregate计算每个路径的总比例,再乘以样本总数得到实际计数。
  • geom_text将计数标签添加到每个堆叠的顶部,vjust = -0.5用于调整标签位置,避免与堆叠条形重叠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:15:30