【发布时间】:2017-01-21 04:08:15
【问题描述】:
我有一个动画,其中数据的范围变化很大。我想要一个 colorbar 来跟踪数据的最大值和最小值(即我不希望它被修复)。问题是如何做到这一点。
理想情况下,我希望 colorbar 在自己的轴上。
我尝试了以下四件事
1。天真的方法
问题:为每一帧绘制一个新的颜色条
#!/usr/bin/env python
"""
An animated image
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax = fig.add_subplot(111)
def f(x, y):
return np.exp(x) + np.sin(y)
x = np.linspace(0, 1, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
frames = []
for i in range(10):
x += 1
curVals = f(x, y)
vmax = np.max(curVals)
vmin = np.min(curVals)
levels = np.linspace(vmin, vmax, 200, endpoint = True)
frame = ax.contourf(curVals, vmax=vmax, vmin=vmin, levels=levels)
cbar = fig.colorbar(frame)
frames.append(frame.collections)
ani = animation.ArtistAnimation(fig, frames, blit=False)
plt.show()
2。添加到图像
把上面的for循环改成
initFrame = ax.contourf(f(x,y))
cbar = fig.colorbar(initFrame)
for i in range(10):
x += 1
curVals = f(x, y)
vmax = np.max(curVals)
vmin = np.min(curVals)
levels = np.linspace(vmin, vmax, 200, endpoint = True)
frame = ax.contourf(curVals, vmax=vmax, vmin=vmin, levels=levels)
cbar.set_clim(vmin = vmin, vmax = vmax)
cbar.draw_all()
frames.append(frame.collections + [cbar])
问题:这引发了
AttributeError: 'Colorbar' object has no attribute 'set_visible'
3。在自己的轴上绘图
问题:colorbar 没有更新。
#!/usr/bin/env python
"""
An animated image
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
def f(x, y):
return np.exp(x) + np.sin(y)
x = np.linspace(0, 1, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
frames = []
for i in range(10):
x += 1
curVals = f(x, y)
vmax = np.max(curVals)
vmin = np.min(curVals)
levels = np.linspace(vmin, vmax, 200, endpoint = True)
frame = ax1.contourf(curVals, vmax=vmax, vmin=vmin, levels=levels)
cbar = fig.colorbar(frame, cax=ax2) # Colorbar does not update
frames.append(frame.collections)
ani = animation.ArtistAnimation(fig, frames, blit=False)
plt.show()
2. 和 4. 的组合。
问题:colorbar 是不变的。
here 发布了一个类似的问题,但看起来 OP 对固定的colorbar 很满意。
【问题讨论】:
-
您与 ArtistAnimation 的关系如何?我不知道该怎么做,但我可以给你一个使用 FuncAnimation 的例子......
-
据我记得,我开始使用 ArtistAnimation,因为我在使用 FuncAnimation 为一些文本作为标题设置动画时遇到了问题。除此之外,我愿意切换回 FuncAnimation。一个例子将不胜感激:)
标签: python animation matplotlib colorbar