如何使用更新函数在Matplotlib中使NetworkX图表动画化?

如何使用更新函数在Matplotlib中使NetworkX图表动画化?

在Matplotlib中使用 更新 函数使 NetworkX 图表动画化,可以参考以下步骤:

  • 设置图表大小并调整子图之间和周围的间距。
  • 使用 figure() 方法创建新图表或激活现有的图表。
  • 使用 边缘、名称和图表属性 初始化图表。
  • 使用 add_nodes_from() 方法向图表中添加节点。
  • 使用Matplotlib绘制带有 G 的图表。
  • 使用 FuncAnimation() 类通过重复调用函数 animate 创建动画。
  • animate 函数清除当前图表,生成两个随机数,并在它们之间绘制边缘。
  • 使用 show() 方法显示图表。

示例

from matplotlib import pyplot as plt, animation
import networkx as nx
import random

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()

G = nx.DiGraph()
G.add_nodes_from([0, 1, 2, 3, 4])

nx.draw(G, with_labels=True)

def animate(frame):
    fig.clear()
    num1 = random.randint(0, 4)
    num2 = random.randint(0, 4)
    G.add_edges_from([(num1, num2)])
    nx.draw(G, with_labels=True)

ani = animation.FuncAnimation(fig, animate, frames=6, interval=1000, repeat=True)

plt.show()
Python

输出

如何使用更新函数在Matplotlib中使NetworkX图表动画化?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册