如何在matplotlib中的补丁圆动画中有效地更改颜色? [英] How to efficiently alter the color in an animation of patches circles in matplotlib?

查看:42
本文介绍了如何在matplotlib中的补丁圆动画中有效地更改颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a visualization for a networking routing simulation, where the network is represented by 2D circle patches in matplotlib.

我正在使用Matplotlib的动画来显示模拟的路由.

I am using Matplotlib's animation to show the simulated routing.

查看Matplotlib.collections,似乎没有一种很好的方法来随机访问圆形对象以快速更改其颜色并重画该集合.

Looking into Matplotlib.collections , it appears there isn't a nice way to random access circle objects in order to quickly alter their color and redraw the collection.

任何关于如何继续的建议将不胜感激!

Any suggestions on how to continue would be greatly appreciated!

目前,我的动画如下:

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

推荐答案

您可以在 patch collection 通过设置集合的颜色映射,然后使用 set_array 在动画的每一步.在下面的示例中,图像数组是随机的,其灵感来自 这个示例.

You can change the color of objects in a patch collection by setting the collection's color map and then changing the image array with set_array at each step of the animation. In the example below the image array is random as inspired by 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()

这篇关于如何在matplotlib中的补丁圆动画中有效地更改颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆