【问题标题】:Create a networkx color_map from OrderedDict elements从 OrderedDict 元素创建一个 networkx color_map
【发布时间】:2018-06-16 01:18:44
【问题描述】:

目标是创建一个基于特征值中心度的 networkx 图,并用不同的节点颜色突出显示中心度最高的前五个节点。

以下是我当前的脚本。它工作正常,现在一切都设置为一种颜色。

#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')

【问题讨论】:

    标签: python dictionary networkx ordereddictionary


    【解决方案1】:

    想通了。无需创建单独的 OrderedDict。将 key=eig.get 参数应用于 sorted() 允许您按值对字典进行排序(此问题的最大障碍)。然后我可以过滤它并将其应用于 cmap。

    【讨论】:

      【解决方案2】:

      不是一个坏问题,但我很确定它是重复的......无论如何,我会尝试回答它。您将不得不原谅我含糊不清,因为我无法运行您的代码,而且我没有尝试编写您的问题的示例。当我稍后可以运行您的代码示例时,我将更新我的答案。但是,现在我相信更改节点颜色类似于更改边缘颜色。从那开始,您需要专注于代码的这一行来更改节点颜色;

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

      我希望这会有所帮助!当我在我自己的机器上测试这个示例时,我稍后会回到它。

      -编辑-

      既然 OP 已经回答了他自己的问题,我将不再用我的例子进一步阐述。但是,如果有人对我的示例感兴趣(但如果不幸抛出任何错误)并希望我修复并扩展它,请给我留言。

      提兹

      【讨论】:

      • 感谢您的回答,蒂兹!不幸的是,熊猫数据框实际上并不包含中心性度量,这是我需要排序的。在您发布之前,我实际上已经解决了一点,并将提交我的答案。感谢您的帮助。
      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 2018-07-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多