Networkx:节点大小必须与维度相关联

时间:2018-03-12 11:30:01

标签: python networkx

我尝试使用networkx在特定位置绘制圆圈。我要绘制的每个圆都有一组坐标和一个半径。

我可以轻松设置坐标:

import networkx as nx
import matplotlib.pyplot as plt

positions = [(0, 0), (36.439507534009273, 0.0),
             (36.439507534009273, -36.439507534009273),
             (36.439507534009273, -72.879015068018546),
             (0.0, -72.879015068018546),
             (2.231276313201516e-15, -109.31852260202781),
             (4.4625526264030319e-15, -145.75803013603709),
             (36.43950753400928, -145.75803013603709),
             (36.43950753400928, -182.19753767004639)]

G = nx.Graph()

pos = dict()

for i, couple in enumerate(positions):
    G.add_node(i)
    print(couple)
    pos[i] = couple


print(G.number_of_nodes())

fig = plt.figure(1)

nodes = nx.draw_networkx_nodes(G, pos)

nx.draw_networkx_edges(G, pos)

plt.axis('equal')
plt.savefig('drawing.png', bbox_inches='tight', dpi=400)
plt.clf()

但我无法正确设置半径。我的例子中的位置以毫米为单位,我圈子的半径也是如此。

enter image description here

我可以设置节点的大小"使用node_size,但我认为我无法将node_size与我的半径相关联。例如,node_size的默认值为300,我不知道它对应的内容。

如果我在位置上有一个圆圈,让我们说(20,20),半径为20,我应该有一个0到40之间的圆圈(x)。

我如何通过networkx实现这一目标?

1 个答案:

答案 0 :(得分:0)

根据您期望绘制的节点数量,您可以采用的一种方法是为每个节点使用matplotlib patches

借鉴https://stackoverflow.com/a/21267406

import networkx as nx
import matplotlib.pyplot as plt
from matplotlib.patches import Circle

# define graph as you did already 
positions = [(0, 0), (36.439507534009273, 0.0),
             (36.439507534009273, -36.439507534009273),
             (36.439507534009273, -72.879015068018546),
             (0.0, -72.879015068018546),
             (2.231276313201516e-15, -109.31852260202781),
             (4.4625526264030319e-15, -145.75803013603709),
             (36.43950753400928, -145.75803013603709),
             (36.43950753400928, -182.19753767004639)]

G = nx.Graph()
pos = dict()
for i, couple in enumerate(positions):
        G.add_node(i)
        print(couple)
        pos[i] = couple


# now make up radius for each node -- default will be 10...
for node in G.nodes():
    G.node[node]['rad'] = 10

# ...but show a bit of variety too
G.node[2]['rad'] = 20
G.node[4]['rad'] = 40
G.node[8]['rad'] = 80

# vector of node radii
rad = [rad for (n, rad) in nx.get_node_attributes(G, 'rad').items()]

# draw nodes manually, with MPL patches.
fig, ax = plt.subplots(1, 1)

for node in G.nodes():
    ax.add_artist(Circle(xy=pos[node], radius=G.node[node]['rad'], 
    facecolor='orange', alpha=0.2, edgecolor='black'))

ax.set_aspect('equal') # important if you want to see *circles*
plt.axis([-150, 200, -300, 25]) # set zoom to view whole image. (patches don't seem to invoke the auto-range setting, unlike scatter does.)

# let's verify they have correct extent
ax.axhline(-10, c='k', ls=':')
ax.axhline(+10, c='k', ls=':')

Circle patches to show dimension of graph