【问题标题】:Change Color & Size of graph in networkx based on degree centrality measure基于度中心性度量更改networkx中图形的颜色和大小
【发布时间】:2021-07-15 08:10:57
【问题描述】:

我要做的是使用 NetworkX 库计算度中心性,然后根据此度量更改不同节点的颜色和大小。

预期的结果是让节点根据其度中心性显示为不同的颜色和大小,但目前,它们只显示默认颜色,因为我不知道我应该这样做。

我在这个项目中使用的 csv 文件可以在这里找到。 https://www.mediafire.com/file/q0kziy9h251fcjf/nutrients.csv/file

该文件目前没有错误消息,除了颜色大小没有改变。

我目前尝试考虑做某种列表理解来解决问题,但我还不确定如何去做,或者如何设置颜色图(什么颜色不重要)

这是我目前正在使用的代码。

import networkx as nx
import matplotlib.pyplot as plt

Data = open('nutrients.csv', "r")
next(Data, None)
Graph_type = nx.Graph()

G = nx.parse_edgelist(Data, delimiter=',', create_using=Graph_type,
                      nodetype=str, data=(('weight', float),))


deg_centrality = nx.degree_centrality(G)
print(deg_centrality)


pos = nx.spring_layout(G)
nx.draw(G, pos)
plt.show()

H

【问题讨论】:

    标签: python python-3.x matplotlib graph networkx


    【解决方案1】:

    这样的事情怎么样?

    import numpy as np
    import matplotlib.colors as mcolors
    import matplotlib.cm as cm
    
    cent = np.fromiter(deg_centrality.values(), float)
    sizes = cent / np.max(cent) * 200
    normalize = mcolors.Normalize(vmin=cent.min(), vmax=cent.max())
    colormap = cm.viridis
    
    scalarmappaple = cm.ScalarMappable(norm=normalize, cmap=colormap)
    scalarmappaple.set_array(cent)
    
    plt.colorbar(scalarmappaple)
    nx.draw(G, pos, node_size=sizes, node_color=sizes, cmap=colormap)
    plt.show()
    

    我引入了一个有点随意的缩放因子,您可以调整它来创建其他尺寸。 Numpy 用于方便的缩放,但您可以使用普通 Python 做同样的事情。

    颜色图可以随意更改:https://matplotlib.org/stable/tutorials/colors/colormaps.html

    编辑:我设法通过改编 this answer 创建了一个颜色渐变图例。

    【讨论】:

      【解决方案2】:

      这是一个带有networkx的绘图功能的简单代码:

      import networkx as nx
      import matplotlib.pyplot as plt
      import numpy as np
      
      # create graph from data
      with open("nutrients.csv", "r") as f:
          G = nx.parse_edgelist(f.readlines(), delimiter=",")
      
      # centrality
      deg_centrality = nx.degree_centrality(G)
      centrality = np.fromiter(deg_centrality.values(), float)
      # plot
      pos = nx.kamada_kawai_layout(G)
      nx.draw(G, pos, node_color=centrality, node_size=centrality*2e3)
      nx.draw_networkx_labels(G, pos)
      plt.show()
      

      输出:

      我强烈建议使用plotly (see exemple) 进行交互。对于这种图表,我觉得它非常有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-27
        • 1970-01-01
        • 2014-05-18
        • 2015-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多