You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python基于经纬度绘制世界机场网络图?

基于经纬度可视化机场网络的Python方案

你可以用 NetworkX + Cartopy 组合实现需求,Cartopy是Python常用的地理可视化库,能轻松添加地图背景,配合NetworkX的绘图API就能生成类似目标效果的机场网络图。如果想要交互式可视化,也可以用Plotly。

核心实现步骤及代码示例

1. 安装依赖库

先安装所需包:

pip install networkx cartopy matplotlib

2. 提取节点经纬度作为布局位置

从你的NetworkX图中,把每个节点的经度、纬度提取出来作为绘图坐标:

import networkx as nx
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature

# 假设你的NetworkX图对象为G
pos = {node: (data['longitude'], data['latitude']) for node, data in G.nodes(data=True)}

3. 绘制带地图背景的网络图

# 创建地图画布,采用PlateCarree投影(适配世界地图展示)
fig, ax = plt.subplots(figsize=(15, 10), subplot_kw={'projection': ccrs.PlateCarree()})

# 添加基础地图元素:海岸线、陆地、海洋
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.LAND, facecolor='lightgray')
ax.add_feature(cfeature.OCEAN, facecolor='lightblue')

# 绘制机场节点(可调整大小、颜色)
nx.draw_networkx_nodes(G, pos, ax=ax, node_size=30, node_color='red', alpha=0.7)

# 绘制航线边(降低透明度避免重叠拥挤)
nx.draw_networkx_edges(G, pos, ax=ax, edge_color='gray', alpha=0.2)

# 设置地图显示范围(聚焦全球)
ax.set_extent([-180, 180, -90, 90])

plt.title("世界机场网络")
plt.show()

交互式可视化方案(Plotly)

如果想要可缩放、hover显示节点详情的交互式图,可使用Plotly:

import plotly.graph_objects as go

# 提取边的坐标数据
edge_x = []
edge_y = []
for edge in G.edges():
    x0, y0 = pos[edge[0]]
    x1, y1 = pos[edge[1]]
    edge_x.extend([x0, x1, None])
    edge_y.extend([y0, y1, None])

# 创建边的轨迹
edge_trace = go.Scatter(
    x=edge_x, y=edge_y,
    line=dict(width=0.5, color='#888'),
    hoverinfo='none',
    mode='lines')

# 创建节点的轨迹
node_x = [pos[node][0] for node in G.nodes()]
node_y = [pos[node][1] for node in G.nodes()]
node_trace = go.Scatter(
    x=node_x, y=node_y,
    mode='markers',
    hoverinfo='text',
    marker=dict(
        showscale=True,
        colorscale='YlGnBu',
        size=8,
        colorbar=dict(
            thickness=15,
            title='节点权重',
            xanchor='left',
            titleside='right'
        )
    )
)

# 添加节点hover提示信息(比如机场名称、经纬度)
node_text = [f"机场: {node}\n纬度: {G.nodes[node]['latitude']}\n经度: {G.nodes[node]['longitude']}" for node in G.nodes()]
node_trace.text = node_text

# 生成交互式图
fig = go.Figure(data=[edge_trace, node_trace],
             layout=go.Layout(
                title='交互式世界机场网络',
                showlegend=False,
                hovermode='closest',
                margin=dict(b=20,l=5,r=5,t=40),
                mapbox=dict(
                    style='open-street-map',
                    center=dict(lon=0, lat=0),
                    zoom=1
                )
             ))
fig.show()

注意事项

  • 确保节点属性中的latitude和longitude是数值类型,避免类型错误。
  • 节点数量过多时,建议调小node_size并降低边的透明度(alpha),避免图面拥挤。
  • Cartopy首次使用可能需要下载地图数据,若卡顿可提前配置数据缓存路径。

内容的提问来源于stack exchange,提问作者Rick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:03:11