如何在matplotlib中更新绘图?

2024-04-24 13:44:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我对在这里重新绘制图形有意见。我允许用户指定时间刻度(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)

Tags: in图形forplotresultlabeldictlist
3条回答

您还可以执行以下操作: 这将在图上绘制50个for循环的10x1随机矩阵数据。

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()

你实际上有两个选择:

  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()

这对我有效。每次都重复调用更新图形的函数。

import matplotlib.pyplot as plt
import matplotlib.animation as anim

def plot_cont(fun, xmax):
    y = []
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)

    def update(i):
        yi = fun()
        y.append(yi)
        x = range(len(y))
        ax.clear()
        ax.plot(x, y)
        print i, ': ', yi

    a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
    plt.show()

“fun”是一个返回整数的函数。 FuncAnimation会反复调用“update”,它会执行“xmax”次。

相关问题 更多 >