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

在RStudio中整理数据集并绘制geom_line/geom_smooth时序图

绘图解决方案

前提假设

你的数据框命名为df,包含以下列:

  • Verstorbene:存储dd-mm格式的日期字符串(或完整日期)
  • year:2015-2022的年份数据
  • y_value:对应y轴的数值(请替换为你实际的列名)

代码实现

1. 加载依赖包并预处理日期

library(ggplot2)
library(lubridate)

# 处理日期:将dd-mm转为统一年份的日期,用于x轴排序
df$date <- dmy(paste0(df$Verstorbene, "-2020"))

2. 绘制geom_line图

ggplot(df, aes(x = date, y = y_value, group = year, color = factor(year))) +
  geom_line(linewidth = 1) +
  scale_x_date(date_labels = "%d-%m", date_breaks = "1 month") +
  scale_y_continuous(limits = c(0, 1000), breaks = seq(0, 1000, 200)) +
  labs(x = "日期", y = "数值", color = "年份") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

3. 绘制geom_smooth图(替换线条为平滑曲线)

ggplot(df, aes(x = date, y = y_value, group = year, color = factor(year))) +
  geom_smooth(method = "loess", se = FALSE) +
  scale_x_date(date_labels = "%d-%m", date_breaks = "1 month") +
  scale_y_continuous(limits = c(0, 1000), breaks = seq(0, 1000, 200)) +
  labs(x = "日期", y = "数值", color = "年份") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

注意事项

  • 务必将代码中的y_value替换为你数据集中对应y轴的列名
  • 如果Verstorbene是包含年份的完整日期,可改用df$date <- as.Date(df$Verstorbene),x轴仍会按日-月展示
  • 若year列不是因子类型,factor(year)会自动将其转为因子,确保图例按年份顺序排列

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 13:15:39