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

如何在Matplotlib中叠加背景网格图与轨迹点图?

问题描述

我用Matplotlib生成了两个图形:一个是通过geopandas读取shp文件并转换坐标系后绘制的背景网格图;另一个是按id分组绘制经纬度轨迹的多组轨迹点图。请问能否将这两个图形叠加显示?

原背景图代码

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize = (10,10))
grid_duomo = gpd.read_file('/content/Griglia_2m-SS.shp')  
grid_duomo.to_crs(epsg=32632).plot(ax=ax, color='lightgrey')

原轨迹点图代码

fig = plt.figure(figsize=(10, 10))
ids = traj_collection_df_new_app['id'].unique()
for id_ in ids:
  self_id = traj_collection_df_new_app[traj_collection_df_new_app['id'] == id_]
  plt.plot(
            self_id['lon'],
            self_id['lat'],
            # markers= 'o',
            # markersize=12
        )

原效果图

背景网格图
轨迹点图

解决方案

当然可以叠加,核心是让两个图形共用同一个Matplotlib的Axes对象,同时必须保证轨迹数据和背景网格的坐标系一致,否则会出现错位。以下是修改后的完整代码:

import matplotlib.pyplot as plt
import geopandas as gpd
from shapely.geometry import Point

# 创建统一的画布和轴对象
fig, ax = plt.subplots(figsize=(10, 10))

# 绘制背景网格(保留原坐标系转换逻辑)
grid_duomo = gpd.read_file('/content/Griglia_2m-SS.shp')
grid_duomo.to_crs(epsg=32632).plot(ax=ax, color='lightgrey')

# 关键步骤:将轨迹数据转换为与背景一致的坐标系
# 假设原始轨迹的lon/lat是WGS84地理坐标系(EPSG:4326)
traj_gdf = gpd.GeoDataFrame(
    traj_collection_df_new_app,
    geometry=gpd.points_from_xy(traj_collection_df_new_app['lon'], traj_collection_df_new_app['lat']),
    crs='EPSG:4326'
)
# 转换为背景使用的EPSG:32632投影坐标系
traj_gdf = traj_gdf.to_crs(epsg=32632)

# 在同一个轴上绘制所有轨迹
ids = traj_gdf['id'].unique()
for id_ in ids:
    self_id = traj_gdf[traj_gdf['id'] == id_]
    # 使用ax.plot而非plt.plot,确保绘制在同一个轴上
    ax.plot(
        self_id.geometry.x,
        self_id.geometry.y,
        marker='o',  # 可选:添加轨迹点标记
        markersize=4,
        linewidth=1,
        label=f'ID: {id_}'  # 可选:添加轨迹图例
    )

# 可选:添加图例、坐标标签和标题
ax.legend()
ax.set_xlabel('东向坐标(米)')
ax.set_ylabel('北向坐标(米)')
ax.set_title('轨迹叠加背景网格')

plt.show()

关键注意事项

  • 共用Axes对象:背景网格绘制时指定ax=ax,轨迹绘制时使用ax.plot(),避免创建新的画布或轴对象
  • 坐标系统一:背景使用的是EPSG:32632(UTM投影,单位为米),而原始轨迹的经纬度是地理坐标系(单位为度),必须转换为相同坐标系才能正确叠加
  • 如果你的轨迹数据本身已经是EPSG:32632坐标系,可以跳过GeoDataFrame转换步骤,直接用self_id['lon']和self_id['lat']绘制轨迹

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:30:54