我正在浏览一本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')
答案 0 :(得分:1)
你可以使用类似于NetworkX的东西。您需要使用与&#34; spring_layout&#34;不同的布局方法。或者像这样明确地设置节点位置:
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')