如何在matplotlib中有效地改变面片圆形动画的颜色?

2024-04-27 05:43:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为网络路由模拟创建一个可视化,其中网络由matplotlib中的2D圆形面片表示。在

我使用Matplotlib的动画来显示模拟的布线。在

调查Matplotlib.集合,似乎没有一个很好的方法来随机访问圆对象,以便快速改变其颜色并重新绘制集合。在

如有任何关于如何继续的建议,我们将不胜感激!在

目前,我的动画如下:

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])

Tags: 网络add路由matplotlib可视化def动画network
1条回答
网友
1楼 · 发布于 2024-04-27 05:43:45

通过设置集合的颜色映射,然后在动画的每个步骤用set_array更改图像数组,可以更改patch collection中对象的颜色。在下面的示例中,图像数组是随机的,灵感来自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()

相关问题 更多 >