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

如何在R语言ggplot2的分组时间序列折线图中手动添加显著性星号?

在ggplot分组折线图中手动添加显著性星号的方法

首先先构造可复用的数据框(对应你提供的数据集):

data <- data.frame(
  Group = rep(c("A", "B", "C", "D", "E"), each = 3),
  Timepoint = rep(1:3, 5),
  Variable = c(1.4705745, 4.6090900, 2.2480962, 1.6443650, 4.4812444,
               0.8026552, 4.7803944, 1.3743527, 4.0399467, 3.5651057,
               4.7275369, 2.4491532, 3.9508347, 3.4278974, 0.6917490)
)

以下是几种手动添加显著性星号的实现方式:

方式一:构造标注数据批量添加

如果需要添加多个星号,先创建包含标注位置和内容的数据框,再用geom_text()绘制:

# 定义标注的位置、星号内容
anno_data <- data.frame(
  x = c(1, 1, 3),   # 对应Timepoint
  y = c(5.2, 5, 5.5),# 星号的y轴位置(高于对应折线)
  label = c("*", "*", "**")
)

# 绘制带星号的折线图
plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group)) +
  geom_line() +
  scale_color_discrete("Group") +
  scale_y_continuous(limits = c(0, 6)) +
  geom_text(data = anno_data, aes(x = x, y = y, label = label),
            inherit.aes = FALSE, size = 5, color = "black")
plot_data
  • inherit.aes = FALSE用于避免继承主图的分组映射,防止出错
  • 可调整size、color参数修改星号的大小和颜色

方式二:用annotate()逐个添加

如果星号数量少,直接用annotate()指定每个星号的坐标:

plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group)) +
  geom_line() +
  scale_color_discrete("Group") +
  scale_y_continuous(limits = c(0, 6)) +
  # 逐个添加星号
  annotate("text", x = 1, y = 5.2, label = "*", size = 5, color = "black") +
  annotate("text", x = 1, y = 5, label = "*", size = 5, color = "black") +
  annotate("text", x = 3, y = 5.5, label = "**", size = 5, color = "black")
plot_data

方式三:给特定分组添加同色星号

如果要让星号颜色和对应组的折线一致,可在标注数据中指定分组,继承颜色映射:

# 定义带分组的标注数据
group_anno <- data.frame(
  Group = c("B", "E", "A"),
  Timepoint = c(1, 1, 3),
  y = c(5.2, 5, 5.5),
  label = c("*", "*", "**")
)

plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group)) +
  geom_line() +
  scale_color_discrete("Group") +
  scale_y_continuous(limits = c(0, 6)) +
  geom_text(data = group_anno, aes(y = y, label = label),
            size = 5, fontface = "bold")
plot_data

内容的提问来源于stack exchange,提问作者r.carnahan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 09:33:29