城市社区划分网络可视化异常:现有代码输出不符合预期需求
城市社区网络图可视化优化问题
数据背景
- 拥有按年份划分社区的城市网络图,各年份的节点社区分配存储在独立数据集(如
community2000对应2000年) - 图G的节点示例:
{'Node': {0: 'albany', 1: 'almaty', 2: 'amsterdam'}}
- 节点间边示例(以albany为例):
{'Source': {0: 'albany', 1: 'albany', 2: 'albany', 3: 'albany', 4: 'albany', 5: 'albany', 6: 'albany', 7: 'albany', 8: 'albany', 9: 'albany'}, 'Target': {0: 'almaty', 1: 'amsterdam', 2: 'ankara', 3: 'athens', 4: 'atlanta', 5: 'auckland', 6: 'austin', 7: 'bangalore', 8: 'bangkok', 9: 'barcelona'}}
- 已通过以下代码为图G的每个节点添加
Community属性:
for node in G.nodes(): city = node community = community_df.loc[community_df['city'] == city, 'cluster'+community_filename[-4:]].values[0] G.nodes[node]['Community'] = community
当前问题
使用以下代码绘制网络图时,输出的图混乱不堪,无法区分社区,不符合预期:
import matplotlib.pyplot as plt # Create a dictionary to map community labels to unique integers community_labels = {} next_community_label = 0 # Assign a unique integer label to each community for node in G.nodes(): community = G.nodes[node]['Community'] if community not in community_labels: community_labels[community] = next_community_label next_community_label += 1 # Create a dictionary to map cluster labels to unique integers within each community cluster_labels = {} # Remove self-loops G.remove_edges_from(nx.selfloop_edges(G)) # Draw the network graph pos = nx.spring_layout(G, k=0.3) # Layout algorithm for node positioning plt.figure(figsize=(12, 8)) for community in community_labels.values(): nodes = [node for node, attr in G.nodes(data=True) if attr['Community'] == community] # Assign cluster labels within each community for node in nodes: cluster = community_df.loc[community_df['city'] == node, 'cluster' + community_filename[-4:]].values[0] cluster_labels[node] = cluster node_colors = [cluster_labels[node] for node in nodes] nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_size=200, node_color=node_colors, cmap='viridis') nx.draw_networkx_edges(G, pos, edgelist=G.edges, alpha=0.1, width=0.5) nx.draw_networkx_labels(G, pos, font_size=8, font_color='black', labels={node: node for node in nodes}) plt.axis('off') plt.title("Network of Cities Divided into Communities and Clusters") plt.tight_layout() plt.show()
期望效果
生成带城市名称节点标签的清晰分社区可视化图,能够明确区分不同社区。
内容的提问来源于stack exchange,提问作者Lusian
相关产品推荐
相关产品推荐

