如何在python

时间:2017-11-15 04:05:31

标签: python numpy animation matplotlib scatter-plot

下面的代码通过散点图每帧30k创建一个600k点的动画。动画完美无瑕,除了我不知道如何在动画中包含我的色彩图(Heatintensity)这一事实。 Xs和Ys正在变化,但点的颜色只是蓝色。

import numpy as np
import matplotlib.pyplot as plt

Heatintensity=workdata[0:600000] #Values controlling scatter colormap
Xs=xCoord[0:600000]
Ys=yCoord[0:600000]

plt.ion()
fig, ax = plt.subplots()
sc = ax.scatter(Xs, Ys, c=Heatintensity, cmap=cm.jet, s=5)

plt.draw()
for i in range(20):
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    fig.canvas.draw_idle()
    plt.pause(0.1)

1 个答案:

答案 0 :(得分:1)

要更改颜色,您需要使用

sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])

除了更改偏移量外。

为了使颜色代表每个动画步骤的相同数值,必须将散布标准化为所有数据,

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())

完整示例:

import numpy as np
import matplotlib.pyplot as plt

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

plt.ion()
fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)

plt.draw()
for i in range(20):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])
    # draw and make pause
    plt.pause(0.1)

plt.ioff()
plt.show()

使用FuncAnimation

可以实现同样的目的
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

Heatintensity=np.random.rand(600000) #Values controlling scatter colormap
Xs=np.random.rand(600000)
Ys=np.random.rand(600000)

fig, ax = plt.subplots()

norm = plt.Normalize(Heatintensity.min(), Heatintensity.max())
sc = ax.scatter(Xs, Ys, c=Heatintensity, s=5, cmap=plt.cm.jet, norm=norm)


def update(i):
    # set coordinates
    sc.set_offsets(np.c_[Xs[(i*30000):(i*30000)+30000],\
                        Ys[(i*30000):(i*30000)+30000]])
    # set colors
    sc.set_array(Heatintensity[(i*30000):(i*30000)+30000])


ani = animation.FuncAnimation(fig, update, frames=range(20), interval=100)

plt.show()