目标是基于特征值中心性创建网络x图,并使用不同的节点颜色突出显示最高中心度量的前五个节点。
以下是我当前的脚本。它工作正常,现在一切都只设置为一种颜色。
#import packages
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import collections
#read data into nx graph
G = nx.from_pandas_dataframe(df, 'col1', 'col2')
#get dictionary of centrality measures and order it
eig = nx.eigenvector_centrality(G)
ordered = collections.OrderedDict(sorted(eig.items(), reverse = True, key=lambda t: t[1]))
#draw graph
nx.draw_spring(G, k=1, node_color = 'skyblue',
node_size = 200, font_size = 6, with_labels = True)
plt.show()
以下是我正在尝试进行节点着色的内容。我正在尝试将前五个有序字典键名附加到color_map,将它们设置为与其余字符不同的颜色。如果您在此处有任何建议或其他方法更简单,请告诉我。如果可能的话,我宁愿坚持我正在使用的包裹。
#adjust color of top three
color_map = []
for key, value in ordered:
if key < 5:
color_map.append('blue')
else: color_map.append('green')
答案 0 :(得分:0)
这不是一个糟糕的问题,但我很确定它是重复的......无论哪种方式,我都会尝试回答它。你必须原谅我的含糊不清,因为我无法运行你的代码而且我没有试图写出你的问题的例子。我将在以后运行您的代码示例时更新我的答案。但是,现在我认为改变节点颜色类似于改变边缘颜色。从那开始,您需要专注于代码的这一行来改变节点颜色;
#draw graph
nx.draw_spring(G, k=1, node_color = 'skyblue',
node_size = 200, font_size = 6, with_labels = True)
这是一个如何做到这一点的例子;
# depending on how your graph is being read from the pandas-
# dataframe this should pull out the correct value to associate-
# the colour with
nodes = G.nodes()
# Just a list to hold all the node colours
node_colours = []
for node in nodes:
if node < 5:
node_colours.append('blue')
else:
node_colours.append('green')
#draw graph, substitute the single colour with ur list of colours
nx.draw_spring(G, k=1, node_color = node_colours,
node_size = 200, font_size = 6, with_labels = True)
我希望这有帮助!稍后当我在自己的机器上测试一个这样的例子时,我会回到它。
-Edit-
由于OP回答了他自己的问题,我不再详细说明我的例子。但是,如果有人对我的示例感兴趣(但如果它不幸地抛出任何错误)并希望我修复它并展开它,请给我留言。
TIZ
答案 1 :(得分:0)
想出来。没有必要创建单独的OrderedDict。将key = eig.get参数应用于sorted()允许您按值对字典进行排序(此问题的最大障碍)。然后我可以过滤它并将其应用于cmap。