matplotlib,使平滑的图形线

时间:2016-12-14 04:52:09

标签: python matplotlib

我无法顺利连接图表上的点。这似乎更难,因为我正在运行一个动画图,我在网上看到的所有例子都是静态图。我试着按照这个插值示例,但我似乎无法让它工作。那里有matplotlib大师吗?这是图表的代码。

import psutil
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
from collections import deque


fig = plt.figure()
ax = plt.axes(xlim=(0, 200), ylim=(0, 100))
line, = ax.plot([],[])

y_list = deque([-1]*200)
x_list = deque(np.arange(200,0,-1))


def init():
    line.set_data([],[])
    return line,


def animate(i):
    y_list.pop()
    y_list.appendleft(psutil.cpu_percent(None,False))
    line.set_data(x_list,y_list)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=100, blit=True)

plt.show()

1 个答案:

答案 0 :(得分:1)

有不同种类的平滑。我们可以考虑显示平均值的线,或过滤函数或样条曲线。我实现了以下三种方法。

import psutil
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
from collections import deque

import scipy.ndimage.filters
import scipy.interpolate


fig = plt.figure()
ax = plt.axes(xlim=(0, 200), ylim=(0, 100))
line, = ax.plot([],[], color="b", label="cpu")
mean_line, = ax.plot([],[], linestyle="--", color="k",label="mean")
filter_line, = ax.plot([],[], linewidth=2, color="r", label="gauss filter")
interp_line, = ax.plot([],[], linewidth=1.5, color="purple", label="spline")

plt.legend()
y_list = deque([-1]*200)
x_list = deque(np.arange(200,0,-1))


def init():
    line.set_data([],[])
    return line,


def animate(i):
    y_list.pop()
    y_list.appendleft(psutil.cpu_percent(None,False))
    line.set_data(x_list,y_list)
    x = np.array(x_list)
    y = np.array(y_list)
    filtered = scipy.ndimage.filters.gaussian_filter1d(y, sigma=4)

    mean_line.set_data(x, np.ones_like(x)*y.mean())
    filter_line.set_data(x,filtered)
    try:
        tck = scipy.interpolate.splrep(x[::-1], y[::-1], s=50000)
        interpolated = scipy.interpolate.splev(x[::-1], tck, der=0)
        interp_line.set_data(x,interpolated[::-1])
    except:
        pass

    return line,filter_line,mean_line,interp_line,

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=100, blit=True)

plt.show()

enter image description here