Networkx:如何从图形中的csv文件添加边缘标签

时间:2020-07-09 12:15:29

标签: python-3.x pandas networkx

如何将csv / excel文件中的Edge标签添加到networkx有向图

我想从csv文件中存在的Edge_label列向我的networkx图添加标签

csv_file

import pandas as pd

import matplotlib.pyplot as plt
#%matplotlib inline

import networkx as nx

df = pd.read_csv('Trail_data.csv')

g = nx.from_pandas_edgelist(df,
                            'Source',
                            'Target',
                             create_using=nx.DiGraph() # For Directed Route arrows
                           ) 

plt.figure( figsize=(40, 40)
          )

nx.draw(g,
        with_labels=True,
        node_size= 3000,#k=200,
        node_color='#82CAFF',##00b4d9
        font_size=16,
        font_weight ='bold',
        font_color='black',
        edge_color = ('#E55451','#810541','#00FF00'),
        node_shape='o',
        width=4 ,
        arrows=True, #Show arrow From and To
        pos=nx.random_layout(g),iterations=20,
        connectionstyle='arc3, rad =0.11' #To avoid overlapping edgs
        
       )

plt.savefig('Visualization.jpeg', 
            dpi = (100)
           )

**另外我还想使用python-dash **将此有向图转换为交互式图

1 个答案:

答案 0 :(得分:1)

根据from_pandas_edgelist的文档,您可以简单地使用edge_attr指定列的列表。

对于您而言,您可以通过以下方式获得所需的图形:

g = nx.from_pandas_edgelist(df,
                            'Source',
                            'Target',
                             edge_attr=`Edge_label`,
                             create_using=nx.DiGraph(),) 

对于绘制,您当前仅绘制节点标签。您可以使用draw_networkx_edge_labels

添加边缘标签
pos = nx.random_layout(g)
nx.draw(g, 
        pos=pos, ...)  # add other parameters
edge_labels = nx.get_edge_attributes(g, "Edge_label")
nx.draw_networkx_edge_labels(g, pos, edge_labels)