如何在地图上可视化带标签的NetworkX图?附代码问题
解决NetworkX + mplleaflet无法显示节点标签的问题
我之前也碰到过这个问题!mplleaflet对NetworkX默认的nx.draw_networkx_labels渲染支持确实有点局限,不过咱们可以手动用matplotlib的文本工具来添加节点标签,亲测有效。
先补全你未写完的代码,然后修改成能显示标签的版本:
import matplotlib.pyplot as plt import mplleaflet import networkx as nx small_graph = nx.Graph() small_graph.add_node('1') small_graph.add_node('2') small_graph.add_node('3') small_graph.add_node('4') small_graph.add_edge('1', '2') small_graph.add_edge('3', '2') small_graph.add_edge('3', '4') # 补全节点位置(假设4的坐标是[58,13]) pos = {'1': [55, 10], '2': [56, 11], '3': [57, 12], '4': [58, 13]} # 先绘制节点和边 nx.draw(small_graph, pos, node_size=500, node_color='red', edge_color='gray') # 手动添加节点标签:遍历每个节点,用plt.text绘制 for node, (x, y) in pos.items(): # 设置文本位置(稍微偏移一点,避免和节点重叠),字体大小和颜色 plt.text(x + 0.05, y + 0.05, node, fontsize=12, color='blue', weight='bold') # 生成Leaflet地图 mplleaflet.show()
关键说明:
- 为什么不用
nx.draw_networkx_labels?因为mplleaflet在转换matplotlib图形时,对NetworkX封装的Text对象的属性(比如坐标转换、渲染优先级)支持不够稳定,手动调用plt.text能更直接地控制文本元素,确保被mplleaflet正确识别。 - 你可以调整
x + 0.05, y + 0.05这个偏移量,让标签和节点的位置更协调;也可以修改fontsize、color等参数自定义样式。
内容的提问来源于stack exchange,提问作者mateuszb
相关产品推荐
相关产品推荐

