Update contourf with colorbar in matplotlib
这是我的测试代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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() |
我在这里感到困惑的是,我画的帧越多,输出图像就越小。有没有办法防止这种情况发生?
。
氧化镁氧化镁
您需要确保颜色条始终位于同一个轴上。为此,您可以在循环外部创建一个颜色条轴(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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() |