Python网络图Matplotlib刷新图

2024-09-29 21:52:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个网络的可视化,该网络包括可移动节点和通过流数据更新的边缘标签。目前,我正在使用randint在绘图时更新pandas数据框

当前代码可以生成节点,并允许它们移动和更新边标签,但它感觉“笨重”,并且每隔一段时间绘图就会闪烁轴(我不想看到)。我似乎无法在netgraph中找到一个好的钩子来简单地刷新图形,而不进行清晰和重新绘制,这将不可避免地随着网络的增长而变得更糟。有人知道我怎样才能让这更顺利吗

以下是当前代码:

import pandas as pd
import matplotlib.pyplot as plt
#plt.ion()
import networkx as nx
import random as r
import netgraph
import numpy as np

#Graph creation:
G=nx.Graph(type="")

#edges automatically create nodes
df=pd.read_csv('diyNodeSet.csv')  
G = nx.from_pandas_edgelist(df, source='sdr', target='rxr', \
    create_using=nx.DiGraph)

#Create edge list from dataframe
df['xy']=list(zip(df.sdr,df.rxr))
ed=list(zip(df.br,df.pct))
el=dict(zip(df.xy,ed))

pos = nx.layout.circular_layout(G)  ##initial node placement

# drag nodes around #########
plot_instance =   netgraph.InteractiveGraph(G,  node_positions=pos, node_color='red', edge_labels=el)

#update the edge labels with random data
import threading
interval = 3

def updatePlot(oldPlot):
    nodePos=oldPlot.node_positions
    new_pct=pd.Series([r.randint(1, 100),r.randint(1, 100),r.randint(1, 100),r.randint(1, 100)], name='pct', index=[0,1,2,3])
    df.update(new_pct)
    ed=list(zip(df.br,df.pct))
    el=dict(zip(df.xy,ed))
    oldPlot.fig.clear()
    global plot_instance
    plot_instance =   netgraph.InteractiveGraph(G,  node_positions=nodePos, node_color='red', edge_labels=el)

#call update each interval    
def startTimer():
    threading.Timer(interval, startTimer).start()
    updatePlot(plot_instance)
   
startTimer()

以下是所需外观的剪报: enter image description here


Tags: instanceimportnodedfplotaszipel
1条回答
网友
1楼 · 发布于 2024-09-29 21:52:51

以下是Netgraph(here)作者的回复,该回复避免了重新绘制绘图并删除了显示的记号:

def updatePlot(plot_instance):
    new_labels = ... # get your label dict
    plot_instance.draw_edge_labels(plot_instance.edge_list, new_labels, 
    plot_instance.node_positions)
    plot_instance.fig.canvas.draw_idle()

这将添加新的边标签并更新现有的边标签。如果要删除边标签,则必须显式删除它们。 艺术家存储在一个字典中,该字典将边映射到艺术家

for edge in edge_labels_to_remove:
    plot_instance.edge_label_artists[edge].remove() # delete artist
    del plot_instance.edge_label_artists[edge] # delete reference

相关问题 更多 >

    热门问题