【问题标题】:How to align nodes and edges in networkx如何对齐networkx中的节点和边
【发布时间】:2016-09-03 20:19:08
【问题描述】:

我正在阅读 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')

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    您可以使用 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')
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 2014-05-25
      • 2013-02-26
      • 2013-12-21
      • 1970-01-01
      • 2019-03-28
      相关资源
      最近更新 更多