【收藏】如何优雅的在 Python matplotlib 中制作平滑线/趋势线
有时候需要在绘制曲线的时候,绘制一条趋势线,如下图,这种如何实现呢,请看下文。
数据如下
趋势计算代码
有两个输入
第一个输入是一个待平滑的数值数组,
第二个输入是权重,越大越平滑
# weight between 0 and 1, the larger the smoother# scalars is the input listdef smooth(scalars, weight): last = scalars[0] # First value in the plot (first timestep) smoothed = list() for point in scalars: smoothed_val = last * weight + (1 - weight) * point # Calculate smoothed value smoothed.append(smoothed_val) # Save it last = smoothed_val # Anchor the last smoothed value return smoothed
出图代码
import pandas as pdimport matplotlib.pyplot as pltimport seaborn as sns# 设置describe 输出的浮点数格式pd.set_option('display.float_format', lambda x: '%.2f' % x)plt.clf()plt.figure(figsize=(10,6))sns.set_theme(style="whitegrid", palette="pastel") # Set2y= "Batch1"df['Y_Trend'] = smooth(list(df[y]), .7) # 计算平滑之后的值sns.lineplot(data=df, x="Epoch", y=y,label=y)sns.lineplot(data=df, x="Epoch", y='Y_Trend',label="Trend Line")plt.ylabel("Accuracy", fontsize=20)plt.xlabel("Epoch", fontsize=20)plt.yticks(fontsize=18)plt.xticks(fontsize=18)plt.legend(loc='lower right', ncol=1, fontsize=20) #vertical legendplt
大功告成