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:
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:
