如何有效地改变matplotlib中贴片圆圈动画的颜色?

时间:2014-05-28 15:28:07

标签: python 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 个答案:

答案 0 :(得分:5)

您可以通过设置集合的颜色映射,然后在动画的每一步都使用patch collection更改图像数组来更改set_array中对象的颜色。在下面的示例中,图像数组是this example启发的随机图像。

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()
相关问题