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

R语言ggplot绘图:基于条件为多数据点添加自定义标签

在ggplot散点图中为特定数据点添加自定义标签

首先修正原代码的小问题:scale_x_discrete(limits = factor(its)) 前面缺少 + 号,会导致代码运行报错,需先补上该符号。

要实现给 pd < -1.5 或 pd > 1.5 的数据点添加带"I"的自定义标签,使用 geom_text() 即可完成,核心是通过筛选目标数据并自定义标签内容:

df <- structure(list(its = 1:20, pd = c(-0.521, -1.866, -0.11, 0.296, 
-0.14, -0.303, 0.141, 0.181, -0.116, 0.475, -0.117, 0.135, -0.139, 
-0.062, -0.098, 1.601, -0.093, -1.993, 2.249, 0.48)), class = "data.frame", row.names = c(NA, -20L))

library(ggplot2)

ggplot(df, aes(x = its, y = pd)) + 
  geom_point(size = 2, shape = 1) +
  geom_hline(yintercept = c(-1.5, 1.5)) +
  # 添加自定义标签
  geom_text(
    subset = .(pd < -1.5 | pd > 1.5),
    aes(label = paste0(its, "I")),
    nudge_y = 0.15, # 微调标签位置避免遮挡散点,可按需调整
    size = 4
  ) +
  theme_bw() +
  labs(x = "", y = "") +
  scale_x_discrete(limits = factor(df$its))

关键说明:

  • subset = .(pd < -1.5 | pd > 1.5):仅对满足条件的数据点应用标签
  • aes(label = paste0(its, "I")):将its字段与"I"拼接成自定义标签文本
  • nudge_y = 0.15:让标签向上偏移一小段距离,避免与散点重叠

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 08:18:16