[英]networkx : Plot a graph with common attributes
我正在嘗試創建一個帶有節點和邊的圖。 我掌握的數據分為成員和他們采取的主題。 現在我以這種形式處理數據,對於每個主題,我都找到了參與該主題的成員:
T498 ['M1', 'M3', 'M5', 'M7', 'M16', 'M20']
T611 ['M2', 'M3', 'M4', 'M6', 'M7', 'M8', 'M9', 'M10', 'M11', 'M12', 'M13', 'M14', 'M15', 'M17', 'M18', 'M19']
如何將這些成員節點加入該主題? 另外,如果我對每個成員都有響應,例如“是”、“否”,我該如何將它們用作權重?
節點和邊就像字典,可以保存您想要的任何類型的信息。 例如,您可以 label 每個節點,無論它是主題還是成員,以及何時到 plot,您可以根據該信息定義其 label、大小、顏色、字體大小等。
這是一個基本示例,您可以根據成員的響應更改每條邊的顏色,而不是根據其厚度或其他屬性。
import matplotlib.pyplot as plt
import networkx as nx
topics = {
'T498': [('M1', 0), ('M3', 1), ('M5', 1), ('M7', 0), ('M8', 0)],
'T611': [('M2', 1), ('M3', 1), ('M4', 0), ('M6', 1), ('M7', 0)],
}
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()
Output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.