Reputation: 12515
I am trying to plot association rules and am having a difficult time getting the node labels below to "follow" the nodes. That is, I would like each label to automatically be near its respective node without having to hard-code any values. The output from below doesn't even include some of the node labels. How can I make these labels dynamically follow the nodes?
import pandas as pd
import networkx as nx
import matlotlib.pyplot as plt
df = pd.DataFrame({'node1': ['candy', 'cookie', 'beach', 'mark', 'black'],
'node2': ['beach', 'beach', 'cookie', 'beach', 'mark'],
'weight': [10, 5, 3, 4, 20]})
G = nx.Graph()
for idx in df.index:
node1 = df.loc[idx, 'node1']
node2 = df.loc[idx, 'node2']
weight = df.loc[idx, 'weight']
G.add_edge(node1, node2, weight = weight)
nx.draw(G, node_size = 100)
pos = nx.spring_layout(G)
nx.draw_networkx_labels(G, pos = pos, font_size = 14, with_labels = True)
plt.draw()
plt.show()
Upvotes: 1
Views: 3105
Reputation: 13021
When you call
nx.draw(G, node_size = 100)
and then
pos = nx.spring_layout(G)
you are creating two sets of positions. The solution is to first get the positions, and then use them for both, nodes and labels.
pos = nx.spring_layout(G)
nx.draw(G, pos = pos, node_size = 100)
# do stuff to pos if you want offsets
nx.draw_networkx_labels(G, pos = pos, font_size = 14, with_labels = True)
Upvotes: 5