如何更新 matplotlib 中的绘图
- 2024-12-06 08:40:00
- admin 原创
- 141
问题描述:
我在这里重新绘制图形时遇到了问题。我允许用户指定时间尺度(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)
解决方案 1:
你实际上有两个选择:
完全按照您当前正在做的事情进行操作,但在重新绘制数据之前调用
graph1.clear()
和。这是最慢但最简单和最强大的选项。graph2.clear()
您可以直接更新绘图对象的数据,而无需重新绘图。您需要对代码进行一些更改,但这应该比每次重新绘图快得多。但是,您绘制的数据形状无法改变,如果数据范围发生变化,您需要手动重置 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()
解决方案 2:
您还可以执行以下操作:这将在 for 循环的 50 个周期内在图上绘制 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()
解决方案 3:
这对我有用:
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()
解决方案 4:
这对我有用。每次重复调用更新图表的函数。
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”次。
解决方案 5:
我发布了一个名为python-drawnow 的包,它提供了让图形更新的功能,通常在 for 循环中调用,类似于 Matlab 的drawnow
。
用法示例:
from pylab import figure, plot, ion, linspace, arange, sin, pi
def draw_fig():
# can be arbitrarily complex; just to draw a figure
#figure() # don't call!
plot(t, x)
#show() # don't call!
N = 1e3
figure() # call here instead!
ion() # enable interactivity
t = linspace(0, 2*pi, num=N)
for i in arange(100):
x = sin(2 * pi * i**2 * t / 100.0)
drawnow(draw_fig)
该包适用于任何 matplotlib 图形,并提供在每次图形更新后等待或放入调试器的选项。
解决方案 6:
如果有人碰巧看到这篇文章并正在寻找我所寻找的内容,我找到了以下示例
如何使用 Matplotlib 可视化标量二维数据?
和
http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop(在 web.archive.org 上)
然后修改它们以使用带有帧输入堆栈的 imshow,而不是动态生成和使用轮廓。
从形状为 (nBins, nBins, nBins) 的 3D 图像数组开始,称为frames
。
def animate_frames(frames):
nBins = frames.shape[0]
frame = frames[0]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
for k in range(nBins):
frame = frames[k]
tempCS1 = plt.imshow(frame, cmap=plt.cm.gray)
del tempCS1
fig.canvas.draw()
#time.sleep(1e-2) #unnecessary, but useful
fig.clf()
fig = plt.figure()
ax = fig.add_subplot(111)
win = fig.canvas.manager.window
fig.canvas.manager.window.after(100, animate_frames, frames)
我还发现了一种更简单但不太健全的方法来完成整个过程:
fig = plt.figure()
for k in range(nBins):
plt.clf()
plt.imshow(frames[k],cmap=plt.cm.gray)
fig.canvas.draw()
time.sleep(1e-6) #unnecessary, but useful
请注意,这两个似乎只适用于ipython --pylab=tk
,又名backend = TkAgg
谢谢你在一切事情上的帮助。
解决方案 7:
以上所有可能都是正确的,但是对我来说,“在线更新”图表仅适用于某些后端,特别是wx
。您可以尝试更改为此,例如通过启动 ipython/pylab ipython --pylab=wx
!祝你好运!
解决方案 8:
根据其他答案,我将图形的更新包装在python装饰器中,以将绘图的更新机制与实际绘图分开。 这样,更新任何绘图都变得更加容易。
def plotlive(func):
plt.ion()
@functools.wraps(func)
def new_func(*args, **kwargs):
# Clear all axes in the current figure.
axes = plt.gcf().get_axes()
for axis in axes:
axis.cla()
# Call func to plot something
result = func(*args, **kwargs)
# Draw the plot
plt.draw()
plt.pause(0.01)
return result
return new_func
使用示例
然后您就可以像使用任何其他装饰器一样使用它。
@plotlive
def plot_something_live(ax, x, y):
ax.plot(x, y)
ax.set_ylim([0, 100])
唯一的限制是你必须在循环之前创建图形:
fig, ax = plt.subplots()
for i in range(100):
x = np.arange(100)
y = np.full([100], fill_value=i)
plot_something_live(ax, x, y)