【收藏】如何优雅的在 Python matplotlib 中制作平滑线趋势线

【收藏】如何优雅的在 Python matplotlib 中制作平滑线趋势线,第1张

有时候需要在绘制曲线的时候,绘制一条趋势线,如下图,这种如何实现呢,请看下文。



数据如下

趋势计算代码

有两个输入
第一个输入是一个待平滑的数值数组,
第二个输入是权重,越大越平滑

# weight between 0 and 1, the larger the smoother
# scalars is the input list
def 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 pd
import matplotlib.pyplot as plt
import 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") # Set2

y= "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 legend
plt

大功告成

对比不同的平滑度(weight)的情况 weight = 0.9

weight = 0.7

weight = 0.3

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/570940.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存