matplotlib에서 플롯을 업데이트하는 방법은 무엇입니까?
여기 그림을 다시 그리는 데 문제가 있습니다. 사용자가 시간 단위 (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)
본질적으로 두 가지 옵션이 있습니다.
당신은 무슨 일을하는지 정확히 모르지만, 전화
graph1.clear()
및graph2.clear()
데이터를 replotting 전에. 가장 느리지 만 가장 단순하고 강력한 옵션입니다.플로팅 대신 플롯 객체의 데이터를 업데이트 할 수 있습니다. 코드를 약간 변경해야하지만 매번 반복하는 것보다 훨씬 빠릅니다. 그러나 플로팅하는 데이터의 모양을 변경할 수 없으며 데이터 범위가 변경되는 경우 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()
다음과 같이 수행 할 수도 있습니다. 이렇게하면 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()
이것은 나를 위해 일했습니다. 매번 그래프를 업데이트하는 함수를 반복해서 호출합니다.
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"번 수행합니다.
내가 찾고있는 것을 찾는 사람 이이 기사를 발견하면 예제를 찾았습니다.
How to visualize scalar 2D data with Matplotlib?
and
http://mri.brechmos.org/2009/07/automatically-update-a-figure-in-a-loop (on web.archive.org)
then modified them to use imshow with an input stack of frames, instead of generating and using contours on the fly.
Starting with a 3D array of images of shape (nBins, nBins, nBins), called 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)
I also found a much simpler way to go about this whole process, albeit less robust:
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
Note that both of these only seem to work with ipython --pylab=tk
, a.k.a.backend = TkAgg
Thank you for the help with everything.
I have released a package called python-drawnow that provides functionality to let a figure update, typically called within a for loop, similar to Matlab's drawnow
.
An example usage:
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)
This package works with any matplotlib figure and provides options to wait after each figure update or drop into the debugger.
All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx
. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx
! Good luck!
참고URL : https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib
'Programing' 카테고리의 다른 글
Enumerable을 사용하는 것이 좋습니다. (0) | 2020.07.02 |
---|---|
C #에서 매개 변수를 사용하여 저장 프로 시저를 호출하십시오. (0) | 2020.07.02 |
Java & = 연산자가 & 또는 &&를 적용합니까? (0) | 2020.07.01 |
언제 ugettext_lazy를 사용해야합니까? (0) | 2020.07.01 |
두 열의 조합에 고유 제한 조건 추가 (0) | 2020.07.01 |