如何在matplotlib中高效改变动画补丁圆的颜色?
我正在制作一个网络路由模拟的可视化,网络通过在matplotlib中显示的2D圆形区域来表示。
我使用Matplotlib的动画功能来展示模拟的路由过程。
在查看Matplotlib.collections时,我发现没有一个简单的方法可以随机访问这些圆形对象,以便快速改变它们的颜色并重新绘制整个集合。
如果有任何建议,我将非常感激!
目前,我的动画代码如下:
def init():
pass
def animate(i):
global network_nodes, active_stack, nums
import matplotlib.artist as mplart
#hard coded routes
n = routes(i)
network_nodes = {}
# draw colorless network
network_gen(levels,0.0,radius,0.0,0.0)
# simplified alterations
network_nodes[n].set_facecolor('blue')
# add the patch
fig.gca().add_patch(network_nodes[c][0])
1 个回答
5
你可以通过设置一个叫做“颜色映射”的东西,来改变一个“补丁集合”中物体的颜色。然后在动画的每一步中,使用一个叫做 set_array 的方法来更新图像数组。在下面的例子中,图像数组是随机生成的,这个灵感来自于 这个例子。
import numpy as np
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import animation
fig, ax = plt.subplots()
patches = []
# create circles with random sizes and locations
N = 10 # number of circles
x = np.random.rand(N)
y = np.random.rand(N)
radii = 0.1*np.random.rand(N)
for x1,y1,r in zip(x, y, radii):
circle = Circle((x1,y1), r)
patches.append(circle)
# add these circles to a collection
p = PatchCollection(patches, cmap=cm.prism, alpha=0.4)
ax.add_collection(p)
def animate(i):
colors = 100*np.random.rand(len(patches)) # random index to color map
p.set_array(np.array(colors)) # set new color colors
return p,
ani = animation.FuncAnimation(fig, animate, frames=50, interval=50)
plt.show()