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

R语言如何将列表对应值标注到各ID独立折线图上

实现代码

你可以按以下代码实现按ID拆分独立折线图、并批量添加对应数值标注的需求:

library(lubridate)
library(tidyverse)

# 基础数据生成
date <- rep_len(seq(dmy("01-01-2010"), dmy("31-12-2013"), by = "days"),1000)
ID <- rep(c("A","B","C", "D", "E"), 100)

df <- data.frame(date = date,
                 x = runif(length(date), min = 60000, max = 80000),
                 y = runif(length(date), min = 800000, max = 900000),
                 ID)

# 你的标注列表
l <- list(1,2,3,4,5,1,2,3,4,5)
l <- setNames(l, c(unique(df$ID), unique(df$ID)))

# 整理标注值映射表
label_map <- enframe(l, name = "ID", value = "tag") %>% 
  group_by(ID) %>% 
  summarise(tags = list(unlist(tag)))

# 批量生成图表
df %>% 
  group_nest(ID) %>% 
  left_join(label_map, by = "ID") %>% 
  mutate(plot = pmap(list(data, ID, tags), function(dt, id, tg) {
    ggplot(dt, aes(date, x)) +
      geom_line(linewidth = 0.3, color = "darkblue") +
      # 添加对应ID的所有数值标注,位置可自行调整
      annotate("text", 
               x = rep(min(dt$date) + 100, length(tg)),
               y = seq(77000, 79000, length.out = length(tg)),
               label = tg, size = 5, color = "red") +
      labs(title = paste("ID", id, "趋势图"), x = "日期", y = "X值") +
      theme_minimal()
  })) -> plot_result

# 查看指定ID的图表,示例为查看ID=A的图
print(plot_result$plot[[which(plot_result$ID == "A")]])

# 批量导出所有图表到本地(可选)
# walk2(plot_result$ID, plot_result$plot, ~ggsave(paste0("ID_", .x, "_折线图.png"), .y, width = 7, height = 4))

效果说明

生成的每张图表对应唯一ID,该ID匹配的所有数值都会标注在图表上,和你预期的效果一致:
目标效果图
你可以根据需要调整annotate内的坐标参数修改标注位置,或者更换ggplot的映射逻辑绘制Y值的折线图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 12:54:05