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

R语言ggplot深度-时间图上添加每日混合层温度MLD_Temp折线的方法

实现思路与代码方案

你可以根据自己的实际需求选择以下两种实现方式:

方案1:红色线代表「混合层临界温度对应的深度」(y轴沿用原有深度轴)

这种方案的逻辑是先给每天的Mn数据匹配当日的MLD_Temp临界值,找到当日温度最接近MLD_Temp的深度,再把这些深度按日期连为折线,符合常见的混合层深度可视化需求。

步骤1:数据预处理

library(dplyr)
library(lubridate)
library(ggplot2)

# 统一两个数据集的日期格式,方便后续按日期关联
Mn <- Mn %>%
  mutate(
    Date_time = ymd_hms(Date_time), # 转换为日期时间格式
    Date = as.Date(Date_time) # 提取日期字段用于匹配MLD数据
  )

MLD <- MLD %>%
  mutate(Date = ymd(Date)) # 转换为日期格式

步骤2:匹配计算每日混合层深度

daily_mld <- Mn %>%
  # 关联当日的混合层临界温度
  left_join(MLD %>% select(Date, MLD_Temp), by = "Date") %>%
  group_by(Date) %>%
  # 筛选当日温度最接近临界温度的观测行,对应的深度即为混合层深度
  filter(abs(Temperature - MLD_Temp) == min(abs(Temperature - MLD_Temp), na.rm = TRUE)) %>%
  ungroup() %>%
  # 每日仅保留一条记录
  distinct(Date, .keep_all = TRUE)

步骤3:绘图

ggplot(Mn, aes(x = Date_time, y = 1-Depth, col = Temperature)) + 
  geom_line(size = 0) + 
  # 新增红色混合层深度折线
  geom_line(data = daily_mld, aes(x = Date_time, y = 1-Depth), color = "red", linewidth = 1) +
  theme(legend.title = element_blank(), legend.position = 'none') +
  xlab("Date") + 
  ylab("Depth")

方案2:红色线直接展示「混合层温度数值」(新增右侧温度Y轴)

如果需要直接展示温度数值,就需要做双Y轴映射:左侧Y轴为深度,右侧Y轴为温度,将MLD_Temp的数值范围缩放后映射到左侧深度轴的范围显示。

步骤1:数据预处理

library(dplyr)
library(lubridate)
library(ggplot2)

Mn <- Mn %>%
  mutate(
    Date_time = ymd_hms(Date_time),
    Date = as.Date(Date_time)
  )

MLD <- MLD %>%
  mutate(
    Date = ymd(Date),
    # 转换为日期时间格式匹配X轴,默认取当日0点,可调整hour参数改为正午等时间点
    Date_time = as.POSIXct(Date, tz = "UTC")
  )

步骤2:计算轴缩放系数

# 计算深度和温度的数值范围
depth_range <- range(1 - Mn$Depth, na.rm = TRUE)
temp_range <- range(MLD$MLD_Temp, na.rm = TRUE)
# 计算温度到深度的缩放因子
scale_factor <- diff(depth_range) / diff(temp_range)

步骤3:绘图

ggplot() +
  # 原有深度时序线
  geom_line(data = Mn, aes(x = Date_time, y = 1-Depth, col = Temperature), size = 0) +
  # 新增红色混合层温度折线,温度值缩放后用左侧深度轴映射
  geom_line(data = MLD, aes(x = Date_time, y = (MLD_Temp - min(temp_range)) * scale_factor + min(depth_range)), color = "red", linewidth = 1) +
  # 配置双Y轴,右侧轴反向缩放显示实际温度值
  scale_y_continuous(
    name = "Depth",
    sec.axis = sec_axis(~ (. - min(depth_range)) / scale_factor + min(temp_range), name = "MLD Temperature")
  ) +
  xlab("Date") +
  theme(legend.title = element_blank(), legend.position = 'none')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:15:03