Python:网络春布局与不同颜色的节点

1 投票
1 回答
1829 浏览
提问于 2025-04-18 00:06

我创建了一个从某个节点出发的最短路径网络,节点是 firm1。我想给每个不同的分离度设置不同的颜色。比如说,连接 firm1 和其他公司的第一条边,比如 firm2firm3,我想把这两个公司的节点颜色改成一样的颜色。接着,所有与 firm2firm3 连接的公司,比如 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 中的公司节点应该是黄色的,等等。

1 个回答

5

做这件事的通用方法是从一个起始节点开始,运行最短路径长度算法来给节点上色。下面是一个例子:

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()

在这里输入图片描述

你也可以使用

positions = nx.spring_layout(G)

来代替。我使用了graphviz的circo布局,因为它更好地绘制了我使用的平衡树。

撰写回答