Networkx:如何在图形中添加来自 csv 文件的边标签

Networkx: how to add edge labels from csv file in a graph

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

我想从 csv 文件

中的第 Edge_label 列向我的 networkx 图表添加标签

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-破折号将这个有向图转换为交互式图 **

根据 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)