Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 18125

How to Create and Visualize a Directed Weighted Graph with Parallel Edges and Different Weights Using Python?

$
0
0

I'm working on a project where I need to create a directed weighted graph in Python that allows parallel edges with different weights between nodes. I am using the networkx library and Matplotlib for visualization.

My goal is to:

  • Create a directed graph with parallel edges (multiple edges between the same nodes).
  • Assign random weights to these edges.
  • Visualize the graph with edge labels showing the weights.
import randomimport networkx as nximport matplotlib.pyplot as pltdef create_graph(n_nodes, alpha = 0.5):    G = nx.MultiDiGraph()    G.add_nodes_from(range(n_nodes))    for i in range(n_nodes):        for j in range(i+1,n_nodes):            if random.random() < alpha:                weight=random.randint(1,10)                G.add_edge(i, j, weight=weight)            if random.random() < alpha:                weight=random.randint(1,10)                G.add_edge(j, i, weight=weight)    return Gdef display_graph(G):    pos = nx.spring_layout(G)      weight_labels = nx.get_edge_attributes(G, 'weight')      nx.draw(G, pos, with_labels=True, node_color='skyblue', edge_color='gray', node_size=700)    nx.draw_networkx_edge_labels(G, pos, edge_labels=weight_labels)      plt.show()n_nodes = 5G = create_graph(n_nodes, alpha = 0.5)display_graph(G)

However, when I try to visualize the graph with edge labels, I got this error message:

networkx.exception.NetworkXError: draw_networkx_edge_labels does not support multiedges.

This error occurs when I try to display edge labels for a MultiDiGraph, and it seems like the draw_networkx_edge_labels function doesn't support parallel edges.

  1. How can I resolve this error and properly visualize a directed weighted graph with parallel edges?
  2. Is there a better way to create and visualize directed graphs with parallel edges in networkx?

I'd appreciate any guidance or examples to help me achieve this. Thank you in advance!


Viewing all articles
Browse latest Browse all 18125

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>