如何生成清晰线图展示EASTVEL与Z_NAP的变化趋势
解决方法
下面几种方法可帮你生成清晰的单条趋势线,可根据数据特性选择合适方式:
1. 按水深分组聚合(推荐用于分层数据)
由于Z_NAP代表水深,同一水深下的海流数据可通过聚合取统计值(均值/中位数),既能减少数据点,又能保留核心趋势:
import pandas as pd import matplotlib.pyplot as plt # 按Z_NAP分组,计算EASTVEL的均值(用median()更稳健,适合有异常值的情况) aggregated_df = frame_3_LW.groupby('Z_NAP')['EASTVEL'].mean().reset_index() # 绘制趋势线 plt.figure(figsize=(8,6)) plt.plot(aggregated_df['EASTVEL'], aggregated_df['Z_NAP'], linewidth=2) plt.xlabel('EASTVEL (东向海流流速)') plt.ylabel('Z_NAP (水深)') plt.title('东向海流流速与水深的趋势关系') plt.gca().invert_yaxis() # 反转y轴,符合"从上到下水深递增"的直观认知 plt.show()
2. 滑动窗口平滑
如果水深是连续变化的,可先按Z_NAP排序,再用滑动窗口对EASTVEL做平滑处理:
# 先按Z_NAP排序,保证数据的连续性 sorted_df = frame_3_LW.sort_values('Z_NAP') # 滑动窗口平滑,window值可根据数据密度调整(比如50个数据点为一个窗口) sorted_df['EASTVEL_smoothed'] = sorted_df['EASTVEL'].rolling(window=50, center=True).mean() # 绘制平滑后的趋势线 plt.figure(figsize=(8,6)) plt.plot(sorted_df['EASTVEL_smoothed'], sorted_df['Z_NAP'], linewidth=2) plt.xlabel('EASTVEL (平滑后东向海流流速)') plt.ylabel('Z_NAP (水深)') plt.title('东向海流流速与水深的平滑趋势') plt.gca().invert_yaxis() plt.show()
注:若平滑后出现NaN值,可添加.dropna()去除,或设置rolling(..., min_periods=1)保留更多数据点。
3. 多项式拟合
用多项式拟合生成整体趋势线,适合呈现数据的宏观变化规律:
import numpy as np # 提取核心数据 x = frame_3_LW['EASTVEL'].values y = frame_3_LW['Z_NAP'].values # 拟合3次多项式(次数可调整,比如2次、4次,需根据实际趋势判断) poly_coeff = np.polyfit(x, y, 3) poly_func = np.poly1d(poly_coeff) # 生成拟合曲线的x值范围,保证曲线平滑连续 x_fit = np.linspace(x.min(), x.max(), 100) y_fit = poly_func(x_fit) # 绘制拟合趋势线 plt.figure(figsize=(8,6)) plt.plot(x_fit, y_fit, linewidth=2, color='red') plt.xlabel('EASTVEL (东向海流流速)') plt.ylabel('Z_NAP (水深)') plt.title('东向海流流速与水深的多项式拟合趋势') plt.gca().invert_yaxis() plt.show()
4. LOWESS局部加权回归平滑
适合捕捉非线性趋势,需先安装statsmodels库:
from statsmodels.nonparametric.smoothers_lowess import lowess # 按Z_NAP排序,保证局部回归的合理性 sorted_df = frame_3_LW.sort_values('Z_NAP') # 应用LOWESS平滑,frac参数控制平滑程度(0-1,值越大曲线越平滑) smoothed_result = lowess(sorted_df['EASTVEL'], sorted_df['Z_NAP'], frac=0.1) # 提取平滑后的数值 y_smoothed = smoothed_result[:, 0] x_smoothed = smoothed_result[:, 1] # 绘制趋势线 plt.figure(figsize=(8,6)) plt.plot(x_smoothed, y_smoothed, linewidth=2) plt.xlabel('EASTVEL (东向海流流速)') plt.ylabel('Z_NAP (水深)') plt.title('东向海流流速与水深的LOWESS平滑趋势') plt.gca().invert_yaxis() plt.show()
内容的提问来源于stack exchange,提问作者Jan Janssen
相关产品推荐
相关产品推荐

