如何更新matplotlib中的图形

216 投票
8 回答
619985 浏览
提问于 2025-04-16 06:34

我在这里遇到了重新绘制图形的问题。我允许用户指定时间轴(x轴)上的单位,然后我会重新计算并调用这个函数 plots()。我希望图表只是更新,而不是在图形上再添加一个新的图表。

def plots():
    global vlgaBuffSorted
    cntr()

    result = collections.defaultdict(list)
    for d in vlgaBuffSorted:
        result[d['event']].append(d)

    result_list = result.values()

    f = Figure()
    graph1 = f.add_subplot(211)
    graph2 = f.add_subplot(212,sharex=graph1)

    for item in result_list:
        tL = []
        vgsL = []
        vdsL = []
        isubL = []
        for dict in item:
            tL.append(dict['time'])
            vgsL.append(dict['vgs'])
            vdsL.append(dict['vds'])
            isubL.append(dict['isub'])
        graph1.plot(tL,vdsL,'bo',label='a')
        graph1.plot(tL,vgsL,'rp',label='b')
        graph2.plot(tL,isubL,'b-',label='c')

    plotCanvas = FigureCanvasTkAgg(f, pltFrame)
    toolbar = NavigationToolbar2TkAgg(plotCanvas, pltFrame)
    toolbar.pack(side=BOTTOM)
    plotCanvas.get_tk_widget().pack(side=TOP)

8 个回答

23

这个对我有效:

from matplotlib import pyplot as plt
from IPython.display import clear_output
import numpy as np
for i in range(50):
    clear_output(wait=True)
    y = np.random.random([10,1])
    plt.plot(y)
    plt.show()
60

你还可以这样做:这段代码会在图表上绘制一个10行1列的随机矩阵数据,循环执行50次。

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()
248

你基本上有两个选择:

  1. 继续按照你现在的做法,但在重新绘制数据之前,先调用 graph1.clear()graph2.clear()。这个方法虽然比较慢,但最简单,也最可靠。

  2. 你可以选择不重新绘制,而是直接更新绘图对象的数据。这样做需要对你的代码做一些修改,但比每次都重新绘制要快得多。不过,你绘制的数据形状不能改变,如果数据范围有变化,你需要手动重置 x 轴和 y 轴的范围。

下面是第二种选择的一个例子:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)

# You probably won't need this if you're embedding things in a tkinter plot...
plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

撰写回答