gpt4 book ai didi

Python:具有不同颜色节点的网络 Spring 布局

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:56 25 4
gpt4 key购买 nike

我创建了一个从给定节点开始的最短路径的 Spring 布局网络。在这种情况下 firm1 .我想为每个分离度使用不同的颜色。例如,所有连接 firm1 的第一条边和其他公司,说 firm2firm3 , 我想更改 firm2 的节点颜色和 firm3 (两者颜色相同)。然后所有从firm2连接的公司和 firm3 ,说 firm4firm5我想改变他们的节点颜色。但我不知道如何为从 firm1 开始的每个分离度更改节点的颜色。 .这是我的代码:

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd

graph = nx.Graph()
with open('C:\\file.txt') as f: #Here, I load a text file with two columns indicating the connections between each firm
for line in f:
tic_1, tic_2 = line.split()
graph.add_edge(tic_1, tic_2)

paths_from_1 = nx.shortest_path(graph, "firm1") #I get the shortest path starting from firm1

x = pd.DataFrame(paths_from_1.values()) #I convert the dictionary of the shortest path into a dataframe


tic_0=x[0].tolist() #there are 7 columns in my dataframe x and I convert each columns into a list. tic_0 is a list of `firm1` string
tic_1=x[1].tolist() #tic_1 is list of all the firms directly connected to firm1
tic_2=x[2].tolist() #tic_2 are the firms indirectly connected to firm1 via the firms in tic_1
tic_3=x[3].tolist() #and so on...
tic_4=x[4].tolist()
tic_5=x[5].tolist()
tic_6=x[6].tolist()

l = len(tic_0)
graph = nx.Graph()

for i in range(len(tic_0)):
graph.add_edge(tic_0[i], tic_1[i])
graph.add_edge(tic_1[i], tic_2[i])
graph.add_edge(tic_2[i], tic_3[i])
graph.add_edge(tic_3[i], tic_4[i])
graph.add_edge(tic_4[i], tic_5[i])
graph.add_edge(tic_5[i], tic_6[i])

pos = nx.spring_layout(graph_short, iterations=200, k=)
nx.draw(graph_short, pos, font_size='6',)
plt.savefig("network.png")
plt.show()

如何为每个分离度设置不同的颜色节点?换句话说,tic_1 中的所有公司应该有一个蓝色的节点,所有公司在 tic_2有黄色节点颜色等

最佳答案

执行此操作的通用方法是从源节点运行最短路径长度算法来分配颜色。这是一个例子:

import matplotlib.pyplot as plt
import networkx as nx

G = nx.balanced_tree(2,5)
length = nx.shortest_path_length(G, source=0)
nodelist,hops = zip(*length.items())
positions = nx.graphviz_layout(G, prog='twopi', root=0)
nx.draw(G, positions, nodelist = nodelist, node_color=hops, cmap=plt.cm.Blues)
plt.axis('equal')
plt.show()

enter image description here

你可以使用

positions = nx.spring_layout(G)

相反。我使用了 graphviz circo 布局,因为它在绘制我使用的平衡树方面做得更好。

关于Python:具有不同颜色节点的网络 Spring 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22679856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com