Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add perpendicular/transversal lines to edge lines in networkx (python)?

I want to add perpendicular/transversal lines to edges according to a ‘weight’.

What I have:

import pandas as pd
import numpy as np
import networkx as nx

G = nx.Graph()
df = pd.DataFrame(
        {'A':["A","A","B","B","C"],
         'B':["B","D","C","D","D"],
         'weight': np.random.randint(1, 10, size=5)
        })


for i, row in df.iterrows():
    G.add_edge(row[0],row[1], label=row[2])
    
pos = nx.fruchterman_reingold_layout(G)
nx.draw(G, pos , with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=nx.get_edge_attributes(G,'label'))

The code generates this image:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

network showing edge weights as values

What I would want is something like this:

network showing edge weights as transversal lines

>Solution :

As a quick hack, instead of passing the weight as a label, format them into a string of "I" letters joined with spaces:

import pandas as pd
import numpy as np
import networkx as nx
from matplotlib import pyplot as plt

G = nx.Graph()
df = pd.DataFrame({
    'A': ["A", "A", "B", "B", "C"],
    'B': ["B", "D", "C", "D", "D"],
    'weight': np.random.randint(1, 10, size=5),
})

# ...

labels = {
    (u, v): ' '.join('I' * weight)
    for (u, v), weight
    in nx.get_edge_attributes(G, 'weight').items()
}
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

Output:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading