Networkx绘图边标签部分超出画布,如何添加左右边距?
解决Networkx绘图边标签超出画布的问题
嘿,作为Networkx新手遇到这个问题太正常啦!我来给你分享几个简单有效的方法,帮你把所有边标签完整显示出来:
方法1:调整画布尺寸和边距
最直接的方式是先创建更大尺寸的画布,再通过subplots_adjust手动设置四周的边距,或者用tight_layout()让Matplotlib自动适配元素位置。
修改后的代码如下:
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() node1 = "116.251.211.248" node2 = "5.79.100.165" node3 = "http.anturis.com" node4 = "s411993.ip-37-187-141.eu" G.add_nodes_from([node1, node2, node3, node4]) # 注意:这里你添加了两条node1-node4的边,Graph会自动保留权重最大的那条哦 G.add_weighted_edges_from([ (node1, node2, 0.742345), (node1, node3, 0.916954), (node1, node4, 0.662011), (node1, node4, 0.818537), (node2, node3, 0.947824), (node2, node4, 0.800774), (node3, node4, 0.928537) ]) # 创建画布和轴对象,设置更大的画布尺寸 fig, ax = plt.subplots(figsize=(10, 8)) pos = nx.shell_layout(G) # 绘制节点和标签 nx.draw(G, pos, with_labels=True, ax=ax) # 绘制边的权重标签 edge_labels = nx.get_edge_attributes(G, 'weight') nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, ax=ax) # 手动调整边距,让标签不被截断 plt.subplots_adjust(left=0.15, right=0.85, top=0.9, bottom=0.1) # 或者用tight_layout自动适配 # plt.tight_layout() plt.show()
方法2:调整标签字体大小
如果画布尺寸不想太大,也可以缩小边标签的字体,避免超出边界。在draw_networkx_edge_labels里添加font_size参数即可:
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, ax=ax, font_size=8)
方法3:调整节点布局
shell_layout有时候会把节点放在画布边缘,你可以尝试换成其他布局(比如spring_layout、circular_layout),可能会自动避免标签超出的问题:
pos = nx.spring_layout(G, seed=42) # seed固定布局,方便重复调试
这些方法单独用或者组合用都能解决你的问题,先试试调整边距和画布尺寸的方法,应该最直接有效~
内容的提问来源于stack exchange,提问作者Sherry
相关产品推荐
相关产品推荐

