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

能否在R中直接基于每日时间序列创建月为X轴年为Y轴的曲面图?

在R中从每日时间序列创建年份-月份曲面图

可以实现,核心是先把每日数据按年份和月份做聚合,再转换成适合曲面图的矩阵结构,最后用绘图工具生成曲面图。以下是具体步骤:

1. 数据预处理

首先修正你代码里的拼写错误(data. Frame → data.frame),然后提取年份、月份信息,再按年月聚合计算数值(这里以月均值为例,你也可以用总和、中位数等统计量):

# 生成数据(修正拼写错误)
dt <- seq(as.Date('2006-01-01'), as.Date('2020-01-31'), by = 1)
temp <- rnorm(5144, mean=21, sd=5)
df <- data.frame(dt, temp)

# 提取年份和月份
df$year <- format(df$dt, "%Y")
df$month <- format(df$dt, "%m")

# 按年月聚合,计算每月温度均值
library(dplyr)
monthly_data <- df %>%
  group_by(year, month) %>%
  summarise(avg_temp = mean(temp, na.rm = TRUE)) %>%
  ungroup()

# 转换成宽格式(矩阵结构,行=年份,列=月份)
wide_data <- tidyr::pivot_wider(monthly_data, names_from = month, values_from = avg_temp)
temp_matrix <- as.matrix(wide_data[,-1])
rownames(temp_matrix) <- wide_data$year

2. 绘制曲面图

方法1:基础R的persp()函数(静态图)

# 定义轴标签和维度
x <- 1:12  # 月份(1-12)
y <- unique(wide_data$year)  # 年份
z <- temp_matrix

# 绘制曲面图
persp(
  x = x,
  y = as.integer(y),
  z = z,
  xlab = "月份",
  ylab = "年份",
  zlab = "平均温度",
  main = "年份-月份温度曲面图",
  theta = 30,  # 旋转角度
  phi = 30,
  col = "lightblue",
  shade = 0.75
)

方法2:plotly包(交互式曲面图)

交互式图支持拖动、缩放查看细节,更直观:

library(plotly)

# 准备数据框格式
plot_data <- reshape2::melt(temp_matrix, varnames = c("year", "month"), value.name = "avg_temp")
plot_data$year <- as.integer(plot_data$year)
plot_data$month <- as.integer(plot_data$month)

# 生成交互式曲面图
plot_ly(
  data = plot_data,
  x = ~month,
  y = ~year,
  z = ~avg_temp,
  type = "surface"
) %>%
  layout(
    scene = list(
      xaxis = list(title = "月份"),
      yaxis = list(title = "年份"),
      zaxis = list(title = "平均温度")
    ),
    title = "年份-月份温度交互式曲面图"
  )

注意:如果每日数据中存在某个年月无数据的情况,需先用tidyr::complete()函数补全缺失的年月,避免矩阵出现NA导致绘图错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:18:21