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

如何用ggplot绘制多州时间序列折线图并添加末端标签?

解决方案

1. 数据预处理

先把示例数据转换成标准数据框,并确保日期列是日期格式:

# 构造示例数据
df <- data.frame(
  Date = as.Date(c("2020-09-01", "2020-10-01", "2020-11-01", "2020-12-01",
                   "2020-09-01", "2020-10-01", "2020-11-01", "2020-12-01",
                   "2020-09-01", "2020-10-01", "2020-11-01", "2020-12-01")),
  State = c("CA", "CA", "CA", "CA", "MA", "MA", "MA", "MA", "AR", "AR", "AR", "AR"),
  Money = c(10,11,12,13,3,4,5,4,6,5,4,6)
)

2. 正确绘制多州折线图

你之前的错误是手动筛选单州数据导致长度不匹配,ggplot可以通过color或group参数自动按州分组绘图:

library(ggplot2)

# 基础多折线图
p <- ggplot(df, aes(x = Date, y = Money, color = State, group = State)) +
  geom_line(linewidth = 1) +
  theme_minimal()

3. 在折线末端添加California标签

提取CA数据的最后一个时间点,用geom_text添加指定标签:

# 获取CA的最新数据点
ca_last <- df[df$State == "CA" & df$Date == max(df$Date), ]

# 添加标签到CA折线末端
p + geom_text(data = ca_last, aes(label = "California"), 
              hjust = -0.2, vjust = 0.5, size = 4)

如果需要给所有折线末端添加对应州名标签,可提取每个州的最后一行数据:

# 获取每个州的最新数据点
last_points <- df[ave(df$Date, df$State, FUN = max) == df$Date, ]

# 绘制带所有州标签的折线图
ggplot(df, aes(x = Date, y = Money, color = State, group = State)) +
  geom_line(linewidth = 1) +
  geom_text(data = last_points, aes(label = State), 
            hjust = -0.2, vjust = 0.5, size = 4) +
  theme_minimal() +
  xlim(min(df$Date), max(df$Date) + 30) # 扩展X轴避免标签超出画布

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 23:06:09