Home > Enterprise >  networkx directed graph can't add weight in the middle of the edges from pandas df
networkx directed graph can't add weight in the middle of the edges from pandas df

Time:11-30

My dataframe columns are A,B,Weight. Around 50 rows

Here is my code

G = nx.from_pandas_edgelist(df, source='A',
                                target='B',
                                create_using=nx.DiGraph())
weight = nx.get_edge_attributes(G, 'Weight')
pos = nx.circular_layout(G, scale=1)
nx.draw(G, pos, with_labels=True)
nx.draw_networkx_nodes(G, pos, node_size=300)
nx.draw_networkx_edges(G, pos=pos, edgelist=G.edges(), edge_color='black')
nx.draw_networkx_labels(G, pos=pos, edge_labels=weight)
plt.show()

It can generate a directed graph that has many edges, and connect A to B. But it still can't display the weight in the middle of the edge, What should I do?

CodePudding user response:

There are two errors that prevented this. First, you need to assign the edge attributes to the graph when defining it. Second, you need to use nx.draw_networkx_edge_labels() and not nx.draw_networkx_labels(). The latter is for node labels, not edge labels.

import pandas as pd
import networkx as nx

df = pd.DataFrame([[1, 2, 4], [3, 4, 2], [1, 3, 1]], columns=['A', 'B', 'Weight'])

G = nx.from_pandas_edgelist(df, source='A',
                                target='B',
                                create_using=nx.DiGraph(),
                                edge_attr='Weight')
weight = nx.get_edge_attributes(G, 'Weight')
pos = nx.circular_layout(G, scale=1)
nx.draw(G, pos, with_labels=True)
nx.draw_networkx_nodes(G, pos, node_size=300)
nx.draw_networkx_edges(G, pos=pos, edgelist=G.edges(), edge_color='black')
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=weight)
plt.show()

plots

graph with edge labels

  • Related