【问题标题】:Python plotting clearing the graph in for loopPython绘图清除for循环中的图形
【发布时间】:2022-12-10 03:16:32
【问题描述】:
我在一个 for 循环中绘图。这样我每次迭代都会得到一个新图。当然,我想清除上一次迭代的图表。当我使用 plt.cla() 时,轴标签和标题也被清除。我怎样才能只删除图表但保留轴标签和标题?
for n in range(N):
ax.plot(x[n],t) # plot
plt.savefig(f'fig_{n}.png') # save the plot
plt.cla()
【问题讨论】:
标签:
python
matplotlib
plot
subplot
【解决方案1】:
试试plt.clf()-clear figure
for n in range(N):
ax.plot(x[n],t) # plot
plt.savefig(f'fig_{n}.png') # save the plot
plt.clf()
【解决方案2】:
删除循环底部的行。
from matplotlib import pyplot as plt
import numpy as np
y = np.arange(10)
fig,ax = plt.subplots()
ax.set_title('foo')
ax.set_ylabel('wye')
ax.set_xlabel('EX')
for n in range(3):
ln, = ax.plot(y*n)
fig.savefig(f'fig{n}')
ln.remove()