非常慢的网络图形动画在Python的matplotlib与networkx

时间:2017-07-03 21:14:17

标签: python animation matplotlib networkx digraphs

我正在制作一个随时间增长的网络图表的动画。我有 它与弯曲的边缘和所有。很高兴,但作为图表 增长速度相当慢!任何人都可以解释或改变给出的代码以更快地运行。我不认为这是我的电脑问题所在。 注意:即使没有花哨的弯曲边缘也很慢。一个简单的nx.draw会导致同样的问题

import time
from matplotlib import pyplot as plt
from matplotlib import animation
import networkx as nx
from matplotlib.patches import FancyArrowPatch, Circle
import numpy as np

mainGraph = nx.DiGraph()
nodeToCoordinate_dict = {}
label_coordinatePositions = {}
edgeLabel_coordinatePositions = {}
edgeLabel_values_dict = {}
fig = plt.figure()


#=============================================================

def draw_network(G,pos,ax,sg=None):
    e = None
    for n in G:
        c=Circle(pos[n],radius=0.02,alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch']=c
        x,y=pos[n]
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1=G.node[u]['patch']
        n2=G.node[v]['patch']
        rad=0.1
        if (u,v) in seen:
            rad=seen.get((u,v))
            rad=(rad+np.sign(rad)*0.1)*-1
        alpha=0.5
        color='k'

        e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=10.0,
                            lw=2,
                            alpha=alpha,
                            color=color)
        seen[(u,v)]=rad
        ax.add_patch(e)

    return e


#========================================================

def animate(i):
    startTime = time.time()
    """perform animation step"""
    global mainGraph, nodeToCoordinate_dict, label_coordinatePositions            

    mainGraph.add_node(str(i%20)+","+str(i/20), pos = (i%20,i/20))
    if not (i%20 == 0):
        mainGraph.add_edge(str(i%20-1)+","+str(i/20), str(i%20)+","+str(i/20))           
        prevNode_coordinate = nodeToCoordinate_dict[str(i%20-1)+","+str(i/20)]

        mainGraph[str(i%20-1)+","+str(i/20)][str(i%20)+","+str(i/20)]['p'] = 1.0
    #END IF    
    nodeToCoordinate_dict[str(i%20)+","+str(i/20)] = (i%20,i/20)                            
    ax=plt.gca()
    draw_network(mainGraph,nodeToCoordinate_dict,ax)
    ax.autoscale()
    plt.axis('equal')
    plt.axis('off')         
    print("time Elapsed = ", time.time()-startTime)
    return None #mainGraph

#====================================================

ani = animation.FuncAnimation(fig, animate, frames= 60,interval=1000)
plt.show()

1 个答案:

答案 0 :(得分:0)

我想我明白了。使用“matplotlib.patches导入FancyArrowPatch,Circle”的函数正在减慢它的速度。这是“draw_network”功能。

我尝试用更简单的(nx.draw(mainGraph,nodeToCoordinate_dict))替换绘图代码,并将时间间隔缩短为100(0.1秒)。像魅力一样工作

现在,我只想找到一种加速曲线边缘图形的方法。