最简单的方法是在matplotlib中启用“交互模式”,该模式会自动在变化上绘制。这是在命令行中做事的好方法,相当于MATLAB如何做。但是,它是速度较慢,所以最好不要使用它在脚本中,所以它不是默认:
import matplotlib.pyplot as plt
x1 = 1
x2 = 2
y1 = 1
y2 = 4
plt.ion() # turn on interactive mode
plt.figure()
plt.xlim(0, 10) # set the limits so they don't change while plotting
plt.ylim(0, 10)
plt.hold(True) # turn hold on
plt.plot(x1, y1, 'b.')
input() # wait for user to press "enter", raw_input() on python 2.x
plt.plot(x2, y2, 'b.')
plt.hold(False) # turn hold off
为一个循环,它的工作是这样的:
import matplotlib.pyplot as plt
import numpy as np
xs = np.arange(10)
ys = np.arange(10)**2
plt.ion()
plt.figure()
plt.xlim(0, 10)
plt.ylim(0, 100)
plt.hold(True)
for x, y in zip(xs, ys):
plt.plot(x, y, 'b.')
input()
plt.hold(False)
如果您使用IPython,但是,您可以使用%pylab
,它负责导入所有内容并启用交互模式:
%pylab
xs = arange(10)
ys = arange(10)**2
figure()
xlim(0, 10) # set the limits so they don't change while plotting
ylim(0, 100)
hold(True)
for x, y in zip(xs, ys):
plot(x, y, 'b.')
input() # raw_input() on python 2.x
hold(False)