使用NetworkX进行动态图绘制(python)

时间:2018-09-13 17:37:53

标签: python matplotlib graph visualization networkx

我有一个使用NetworkX的带有一组节点的图。在每次迭代时,我都会在这些点之间生成一条随机路径。

我想在每次迭代中绘制图形,但我不想每次都绘制新图形,我只想在生成新图形时用新图形更新图形。。< / p>

我看过很多解决方案,但似乎都无法正确回答我的问题

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import math
import random

# Simple distance function
def dist(p1=None, p2=None):
    if(p1 == None or p2 == None):
        raise ValueError('You need to give 2 points in a tuple form like p1 = (x1,y1) and p2 = (x2,y2)')
    distance =  math.sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 )
    return distance

for i in range(3):
    random.shuffle(path)

    G = nx.Graph()
    G.add_nodes_from(points)

    # Nothing important here, just put edges between nodes
    for i in range(len(path)):
        if(i+1 < len(path)):
            G.add_edge(path[i], path[i+1], weight=dist(points[path[i]],points[path[i+1]]))

    fig = plt.figure(figsize=(12,8)) 
    nx.draw_networkx_nodes(G, points, node_size=300) #draw nodes
    nx.draw_networkx_edges(G, points, edgelist=G.edges) #draw edges
    nx.draw_networkx_labels(G, points)

    plt.rcParams['figure.facecolor'] = 'white'
    plt.pause(0.1)

plt.show()

您可以尝试我的代码,它会生成3个窗口,每个窗口都有一个图。我想随着数据的变化更新一个窗口和一个图。我认为不需要使用Animation,但显然我不是专家

0 个答案:

没有答案