如何将颜色图添加到matplotlib动画中?

时间:2018-06-25 06:24:22

标签: python animation matplotlib

假设我正在尝试使用其X和Y轴位置并使用其他变量“ Z”作为颜色图来可视化对象位置。下面的简化示例说明了我目前的操作方式。

import numpy as np
from matplotlib import pyplot as plt

dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)

plt.scatter(dataX, dataY, c=dataZ, cmap='winter', edgecolors='none')
plt.colorbar()
plt.show()

和结果: enter image description here

我想为此添加一个实时动画,而不仅仅是显示静态图像,但是我正在努力为其添加色彩图。下面的代码显示了我如何没有使用颜色表。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import Tkinter
import tkMessageBox

def restart():
    root = Tkinter.Tk()
    root.withdraw()
    result = tkMessageBox.askyesno("Restart", "Would you like to restart the animation?")
    if result:
        ani.frame_seq = ani.new_frame_seq() 
        ani.event_source.start()
    else:
        plt.close()

dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)


def function(num, dataX,dataY, line):
    line.set_data(dataX[..., :num],dataY[..., :num])
    if num == dataX.size :
        restart()
    return line,

fig = plt.figure()

l, = plt.plot([], [], 'ro', markeredgewidth=0.0)
limitsX = [min(dataX)-100,max(dataX)+100]
limitsY = [min(dataY)-100, max(dataY)+100]
plt.xlim(limitsX[0],limitsX[1] )
plt.ylim(limitsY[0],limitsY[1] )
plt.xlabel('x')
plt.ylabel('y')
plt.title('test')

ani = animation.FuncAnimation(fig, function, (dataX.size+1), fargs=(dataX,dataY,l),
                              interval=10, blit = True, repeat = False)

plt.show()

再问一个问题:如何为动画添加色彩图?

1 个答案:

答案 0 :(得分:1)

尽管我认为处理PathCollection的特定情况(由scatter()返回)确实需要一个新的答案,但是这个答案大致基于my answer to a similar problem

这是我解决问题的方法。诀窍是在图中的第二个轴上生成单独的静态颜色条。然后,在更新PathCollection属性时,使用该颜色条和规范化来更新点的颜色。

dataX = np.linspace(-50,50,1000)
dataY = np.linspace(-50,50,1000)
dataZ = np.linspace(-50,50,1000)


def animate(num):
    data = np.hstack((dataX[:num,np.newaxis], dataY[:num, np.newaxis]))
    art.set_offsets(data)
    art.set_color(cmap(norm(dataZ[:num]))) # update colors using the colorbar and its normalization defined below
    return art,


fig,[ax,cax] = plt.subplots(1,2, gridspec_kw={"width_ratios":[50,1]})
# Set the colormap and norm to correspond to the data for which
# the colorbar will be used.
cmap = matplotlib.cm.winter
norm = matplotlib.colors.Normalize(vmin=-50, vmax=50)

cb1 = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap,
                                norm=norm,
                                orientation='vertical')

ax.set_xlim(-60,60)
ax.set_ylim(-60,60)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('test')
art = ax.scatter([],[],c=[])

ani = animation.FuncAnimation(fig, animate,interval=2, blit=True, repeat=True)

plt.show()

enter image description here