这是我的测试代码。
import os
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
bb, cc = np.meshgrid(a, a)
u = np.random.randint(2, 4, (10, 10))
v = np.random.randint(2, 4, (10, 10))
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
plt.subplots_adjust(left=0.07, bottom=0.01, right=0.95,
top=0.94, hspace=0.0, wspace=0.0)
for i in range(10):
u = np.random.randint(2, 4, (10, 10))
v = np.random.randint(2, 4, (10, 10))
ws = np.sqrt(u**2 + v**2)
cf = plt.contourf(bb, cc, ws)
cb = plt.colorbar(cf)
fig.canvas.update()
fig.canvas.flush_events()
plt.savefig('test_barb/%i.png' % i, dpi=200)
for c in cf.collections:
c.remove()
cb.remove()我发现令人困惑的是,我画的帧越多,输出的图像就越小。有什么方法可以防止这种情况发生吗?



发布于 2017-10-12 01:00:27
您可能希望确保颜色栏始终位于相同的轴上。为此,您可以在循环外创建一个颜色条轴(cax),例如使用axes_divider,并始终将颜色条绘制到该轴fig.colorbar(cf, cax=cax)。
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
import numpy as np
a = np.arange(10)
bb, cc = np.meshgrid(a, a)
u = np.random.randint(2, 4, (10, 10))
v = np.random.randint(2, 4, (10, 10))
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
# create axes for the colorbar
cax = make_axes_locatable(ax).append_axes("right", size="5%", pad="2%")
for i in range(10):
# clear colorbar axes
cax.clear()
u = np.random.randint(2, 4, (10, 10))
v = np.random.randint(2, 4, (10, 10))
ws = np.sqrt(u**2 + v**2)
cf = ax.contourf(bb, cc, ws)
# draw new colorbar in existing cax
cb = fig.colorbar(cf, cax=cax)
fig.canvas.update()
fig.canvas.flush_events()
#plt.savefig('test_barb/%i.png' % i, dpi=200)
plt.show()https://stackoverflow.com/questions/46690420
复制相似问题