Sib
Sib

Reputation: 483

How to plot networkx graph with several edge attributes?

I have a graph where each edge has two attributes 'mark' and 'cable_name'. My goal is to plot it with displaying both attributes at once, one above another one:

import networkx as nx
import matplotlib.pyplot as plt    

G = nx.Graph()
G.add_edge(1, 2,  mark='200', cable_name='К300')

pos = nx.spring_layout(G, scale=2)    
edge_labels = nx.get_edge_attributes(G, 'mark')
nx.draw_networkx_edge_labels(G, pos, edge_labels)
nx.draw(G, with_labels = True, nodecolor='r', edge_color='b')
plt.show()

enter image description here

It shows just one attribute 'mark', as I get from documentation for get_edge_attributes function its attribute 'name' in can only be a string, not a list of strings.

Is there any proper possibility to display both attributes in the way like this?

enter image description here

Upvotes: 2

Views: 1953

Answers (1)

abc
abc

Reputation: 11929

You can customize the edge labels by associating to the key (i.e., the edge) the label to be displayed on the plot.

Example:

  1. Formatted label

    edge_labels = {}
    # this assumes all the edges have the same labels 'marks' and 'cable_name' 
    for u, v, data in G.edges(data=True):
        edge_labels[u, v] = f"{data['mark']}\n{data['cable_name']}"
    
  2. Adding the whole dict with the attributes as an edge label

    edge_labels = {}
    for u, v, data in G.edges(data=True):
        edge_labels[u, v] = data
    

Upvotes: 4

Related Questions