python - 如何更快地制作使用 networkx 的 matplotlib 动画?
问题描述
下面的代码运行一个函数(showNet)100 次。该函数采用节点标签列表来更新网络图。现在,代码大约需要 16.55 秒才能完成,这意味着 100 帧/图形更新中的每一个都需要 16.55 / 100 = 0.16 秒。这比我的需要少。
我的问题是,有什么办法可以让这更快吗?我知道有一些解决方案,如多处理或 blit,但老实说,我不知道如何在 matplotlib 中使用它们。
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import random
import time
global ax, fig, G
fig, ax = plt.subplots(figsize=(10,7))
G = nx.DiGraph()
def showNet(n):
global ax, fig, G
plt.style.use('Solarize_Light2')
fig.clf()
l1, l2, l3, l4, l5, l6, l7 = n[0], n[1], n[2], n[3], n[4], n[5], n[6]
edgelist= [(l1,l2),(l2,l3), (l3,l4), (l3,l5), (l4, l1), (l5, l6), (l5, l7)]
pos = {l1: (10, 60), l2: (10, 40), l3:(80, 40), l4:(140, 60), l5:(200, 20), l6:(250, 40), l7:(250,10)}
ax = nx.draw_networkx_nodes(G, pos=pos, nodelist=list(pos.keys()), node_size=2000, alpha=1)
ax = nx.draw_networkx_edges(G, pos=pos, edgelist= edgelist , edge_color="gray", arrows=True, arrowsize=10, arrowstyle='wedge')
ax = nx.draw_networkx_labels(G, pos=pos, labels=dict(zip(pos.keys(),pos.keys())), font_color="black")
# Hide grid lines
plt.grid(False)
plt.ion()
fig.show()
plt.pause(0.0000001)
start = time.perf_counter()
for i in range(100):
n = random.sample(range(1, 10), 7)
showNet(n)
finish = time.perf_counter()
print(finish - start)
解决方案
推荐阅读
- rxjs - RXjs:将 2 个开关图组合成 1 个?
- vuejs3 - 试图让复选框与 amcharts 4 地图点击事件一起使用
- amazon-web-services - 如何启动具有包依赖项的 AWS 云形成堆栈?
- bluetooth-lowenergy - 为 ESP32 设置安全 BLE 连接
- php - Laravel updateOrInsert 基于 whereBetween 的数据透视表
- mongodb - 批量删除mongodb中的文档
- c - free():释放二维指针时指针无效
- javascript - 一个变量在我的 JavaScript 工厂函数中没有得到更新
- reactjs - 在反应测试库中测试useEffect + jest
- php - MySQL 标签系统 - 如何选择与最后 N 个发布的帖子关联的所有标签?