使用离散字符串 x 轴平滑 matplotlib 图?

问题描述

我试图在 matplotlib 中绘制一个平滑的折线图,其中 离散 x 轴是字符串(请参见下面的输出图)。我目前得到锯齿状的线条。我在 Stack Overflow 上看到的所有示例都处理连续的 x 轴 (example),并依赖于利用 x 轴表示 linspace()spline 来自 {{1} }.这是给出锯齿状线条的绘图代码的摘录:

scipy.interpolate

这是输出

enter image description here

我希望平滑后的输出看起来像这样(右侧),但我的 x 轴是一个字符串

enter image description here

对此的任何帮助将不胜感激!

解决方法

SciPy's interpolate module documentation逐字复制的示例代码:

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt

x = np.linspace(0,10,num=11,endpoint=True)
y = np.cos(-x**2/9.0)

f = interp1d(x,y)
f2 = interp1d(x,y,kind='cubic')

xnew = np.linspace(0,num=41,endpoint=True)

plt.plot(x,'o',xnew,f(xnew),'-',f2(xnew),'--')
plt.legend(['data','linear','cubic'],loc='best')
plt.show()

这会产生:

enter image description here

更多信息在 scipy.interpolate.interp1d 的文档中。

让我补充一点,您确实通过评论中提到的这种情节歪曲了数据。您确实将信息添加到原始数据中。合理的操作将是线性插值(np.polyfitdeg=1)或 moving average