【问题标题】:matplotlib, make smooth graph linematplotlib,制作平滑的图形线
【发布时间】:2016-12-14 04:52:09
【问题描述】:

我无法使连接图表上各点的线平滑。这似乎更困难,因为我正在运行一个动画图,我在网上看到的所有示例都是静态图。我尝试遵循这个插值示例,但我似乎无法让它工作。那里有任何 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()

【问题讨论】:

  • @MikeJSChoi 不是重复的。在这里的这个问题中,'smooth' 是指屏幕上线条的平滑,而在链接问题中,'smooth' 是指动画中的过渡。
  • @HexxNine 什么是“这个插值示例”?你能链接到它吗?您还需要说出平滑线的确切含义?一条直线,显示平均值还是曲线?其他插值示例在多大程度上不适合您?问题到底出在哪里?
  • @ImportanceOfBeingErnest 这是我所指的链接,我想我把它放在上面猜我忘了:P docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html

标签: python matplotlib


【解决方案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()

【讨论】:

    猜你喜欢
    • 2013-01-20
    • 2014-11-07
    • 1970-01-01
    • 2021-09-06
    • 2023-03-22
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    相关资源
    最近更新 更多