简体   繁体   中英

Plotting networkx graph: node labels adjacent to nodes?

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()

在此处输入图片说明

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM