微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

networkx :绘制具有共同属性的图

如何解决networkx :绘制具有共同属性的图

我正在尝试创建一个带有节点和边的图。我拥有的数据分为成员和他们所采取的主题。现在我以这种形式处理数据,其中对于每个主题,我都找到了选择该主题的成员:

T498    ['M1','M3','M5','M7','M16','M20']                  
T611    ['M2','M4','M6','M8','M9','M10','M11','M12','M13','M14','M15','M17','M18','M19']

如何将这些成员节点加入该主题? 另外,如果我对每个成员都有诸如“是”、“否”之类的回答,我如何将它们用作权重?

解决方法

节点和边就像字典,可以保存您想要的任何类型的信息。例如,您可以标记每个节点是主题还是成员,何时需要绘制,您可以根据该信息定义其标签、大小、颜色、字体大小等。

这是一个基本示例,您可以根据成员的响应更改每条边的颜色,而不是根据其粗细或某些其他属性。

import matplotlib.pyplot as plt
import networkx as nx

topics = {
    'T498': [('M1',0),('M3',1),('M5',('M7',('M8',0)],'T611': [('M2',('M4',('M6',}

G = nx.Graph()
for topic,members in topics.items():
    # You just need `G.add_node(node)`,everything else after that is an attribute
    G.add_node(topic,type='topic')
    for member,response in members:
        if member not in G.nodes:
            G.add_node(member,type='member')
        # `G.add_edge(node1,node2)`,the rest are attributes
        G.add_edge(topic,member,response=response)

node_sizes = [1000 if attrs['type'] == 'topic' else 500 for attrs in G.nodes.values()]
node_colors = ['r' if attrs['type'] == 'topic' else '#1f78b4' for attrs in G.nodes.values()]
edge_colors = ['y' if attrs['response'] else 'k' for attrs in G.edges.values()]
pos = nx.spring_layout(G)
nx.draw_networkx_labels(G,pos)
nx.draw(G,pos,node_size=node_sizes,node_color=node_colors,edge_color=edge_colors)
plt.show()

输出

1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。