繁体   English   中英

如何对齐networkx中的节点和边

[英]How to align nodes and edges in networkx

我正在阅读 O'Reilly 数据科学书籍,它为您提供了或多或少创建此节点的 python 代码,即...

在此处输入图像描述

但它并没有告诉你如何制作可视化,因为它与主题并不真正相关,但我还是想尝试一下,到目前为止,这与我已经接近了

users = [
{ "id": 0, "name": "Hero" },
{ "id": 1, "name": "Dunn" },
{ "id": 2, "name": "Sue" },
{ "id": 3, "name": "Chi" },
{ "id": 4, "name": "Thor" },
{ "id": 5, "name": "Clive" },
{ "id": 6, "name": "Hicks" },
{ "id": 7, "name": "Devin" },
{ "id": 8, "name": "Kate" },
{ "id": 9, "name": "Klein" },
{ "id": 10, "name": "Jen" }
]

friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 3), (3, 4),
           (4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]

import networkx as nx
import matplotlib as plt
%matplotlib inline
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos, node_size=1000)

在此处输入图像描述

这对我来说是全新的 python 和 networkx - 我似乎无法从他们的文档中弄清楚我应该使用什么实际图表 - 我几乎尝试了其中的每一个,但没有一个能让我到达那里 - 在 networkx 中是否有可能以这种方式对齐节点,使用什么正确的图形?

networkx 是这项工作的正确工具吗?这项任务有更好的 python 库吗?

更新

@Aric 答案很完美,但我做了一些更改以使节点匹配数据而不是静态类型数组。 我不认为这是进行计算的“最佳”方法,具有更多 python 经验的人会更清楚。 我玩了一段时间的最小尺寸和位置,但我仍然无法让它像素完美,但我仍然对最终结果感到非常满意

import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = {0: [0,0],
       1: [4,-0.35],
       2: [4,0.35],
       3: [8,0],
       4: [12,0],
       5: [16,0],
       6: [20,0.35],
       7: [20,-0.35],
       8: [24,0],
       9: [28,0],
       10: [32,0]}

nodes = [user["id"] for user in users]
def calcSize(node):
    minSize = 450
    friends = number_of_friends(node)
    if friends <= 0:
        return minSize
    return minSize * friends

node_size = [(calcSize(user)) for user in users]
nx.draw_networkx(G, pos, nodelist=nodes, node_size=node_size, node_color='#c4daef')
plt.ylim(-1,1)
plt.axis('off')

你可以用 NetworkX 做类似的事情。 您需要使用与“spring_layout”不同的布局方法或像这样明确设置节点位置:

import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_nodes_from([user["id"] for user in users])
G.add_edges_from(friendships)
pos = {0: [0,0],
       1: [1,-0.25],
       2: [1,0.25],
       3: [2,0],
       4: [3,0],
       5: [4,0],
       6: [5,0.25],
       7: [5,-0.25],
       8: [6,0],
       9: [7,0],
       10: [8,0]}

nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
node_size = [500, 1000, 1000, 1000,  500, 1000, 500, 500 , 1000, 300, 300]
nx.draw_networkx(G, pos, nodelist=nodes, node_size=node_size, node_color='#c4daef')
plt.ylim(-1,1)
plt.axis('off')

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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