MatPlotLib的ion()和draw()无法正常工作 [英] MatPlotLib's ion() and draw() not working
问题描述
我正在尝试使用for循环实时绘制图形.我有以下简单代码:
I am trying to plot figures in real time using a for loop. I have the following simple code:
import matplotlib.pyplot as plt
plt.ion()
plt.figure()
for i in range(100):
plt.plot([i], [i], 'o')
plt.draw()
plt.pause(0.0001)
此代码在完成计算之前不会显示该数字,我不希望这样做.我希望它在每个循环之后绘制图形.如果将plt.draw()
替换为plt.show
,则会实时输出多个图形,但是我希望它们全部出现在同一图形中.有什么想法吗?
This code does not show the figure until it has finished computing, which I don't want. I want it to draw the figure after every loop. If I replace plt.draw()
with plt.show
, multiple figures are output in real time, but I want them all to appear in the same figure. Any ideas?
我用Anaconda下载了PyCharm,一切正常.我猜这是Spyder的问题,因为我尝试了几种不同的版本而没有成功.如果有人知道是什么原因导致Spyder出现此问题,请告诉我!
I downloaded PyCharm with Anaconda and everything works fine. I guess it's a problem with Spyder since I tried a few different versions of it without success. If anyone has any clue what is causing this problem in Spyder, let me know!
推荐答案
适用于您的案例,来自: Python实时绘图
Adapted for your case from : Python realtime plotting
import matplotlib.pyplot as plt
import numpy as np
import time
fig = plt.figure()
ax = fig.add_subplot(111)
# some X and Y data
x = [0]
y = [0]
li, = ax.plot(x, y,'o')
# draw and show it
fig.canvas.draw()
plt.show(block=False)
# loop to update the data
for i in range(100):
try:
x.append(i)
y.append(i)
# set the new data
li.set_xdata(x)
li.set_ydata(y)
ax.relim()
ax.autoscale_view(True,True,True)
fig.canvas.draw()
time.sleep(0.01)
except KeyboardInterrupt:
plt.close('all')
break
这篇关于MatPlotLib的ion()和draw()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!