【问题标题】:Plot distribution of node attributes networkx绘制节点属性networkx的分布图
【发布时间】:2021-10-25 15:57:13
【问题描述】:

有向图中的节点具有NameAgeHeight 作为属性。我想绘制三个属性的分布,可以吗?

我知道可以这样获取属性:

name = nx.get_node_attributes(G, "Name")
age = nx.get_node_attributes(G, "Age")
height = nx.get_node_attributes(G, "Height")

但我真的不明白如何在下面的函数中使用这些而不是 G

import networkx as nx

def plot_degree_dist(G):
    degrees = [G.degree(n) for n in G.nodes()]
    plt.hist(degrees)
    plt.show()

plot_degree_dist(nx.gnp_random_graph(100, 0.5, directed=True))

或者有没有更好的方法来绘制节点属性的分布?

【问题讨论】:

    标签: python matplotlib networkx


    【解决方案1】:

    对我来说似乎是一种完全合理的方式。我不知道任何更方便的方法。为了更通用,向您的函数添加一个参数,该参数采用您要绘制的属性的名称。

    只要知道nx.get_node_attributes() 返回一个键控到节点的字典。由于我们只是在绘制分布图,因此我们只对值感兴趣,而不对键感兴趣。

    下面是一个独立的例子:

    import networkx as nx
    import matplotlib.pyplot as plt
    import numpy as np
    
    
    def plot_attribute_dist(G, attribute):
        attribute = nx.get_node_attributes(G, attribute).values()
        plt.hist(attribute)
        plt.show()
    
    
    attribute_name = 'Name'
    
    G = nx.gnp_random_graph(100, 0.5, directed=True)
    
    rng = np.random.default_rng(seed=42)
    for node, data in G.nodes(data=True):
        data[attribute_name] = rng.normal()
    
    plot_attribute_dist(G, attribute_name)
    

    哪个输出

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-26
      • 2019-10-11
      • 2017-03-29
      • 1970-01-01
      相关资源
      最近更新 更多