当前位置:首页 > Python > 正文

Python教程:如何在地图上绘制比例尺 | 地理可视化技巧

Python地图可视化:如何添加专业比例尺

在制作专业地图时,比例尺是必不可少的元素。本教程将教你使用Python的Cartopy和Matplotlib库,通过5个简单步骤实现地图比例尺的添加。

准备工作

安装所需库:

pip install cartopy matplotlib numpy

完整代码示例

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import numpy as np

def add_scale_bar(ax, length_km, location=(0.05, 0.05)):
    """添加比例尺到地图"""
    # 获取地图坐标转换
    transform = ccrs.PlateCarree()._as_mpl_transform(ax)
    
    # 计算比例尺位置
    x, y = location[0], location[1]
    
    # 绘制比例尺主线
    ax.plot([x, x + length_km/110], [y, y], 
            color='black', linewidth=2, transform=transform)
    
    # 添加刻度标记
    for pos in np.linspace(0, length_km/110, 5):
        ax.plot([x + pos, x + pos], [y, y-0.01], 
                color='black', linewidth=1, transform=transform)
    
    # 添加文本标签
    ax.text(x + (length_km/110)/2, y-0.02, f'{length_km} km', 
            ha='center', va='top', transform=transform,
            fontsize=9, backgroundcolor='white')

# 创建地图
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
ax.coastlines(resolution='50m')
ax.gridlines(draw_labels=True)

# 添加比例尺
add_scale_bar(ax, length_km=500, location=(0.05, 0.1))

plt.title('中国地图 - 含比例尺')
plt.savefig('map_with_scale.png', dpi=300)
plt.show()

关键参数说明

  • length_km - 比例尺表示的实际公里数
  • location - (x,y)元组控制比例尺位置(0-1相对坐标)
  • transform - 确保比例尺正确投影到地图上
  • linewidth - 控制比例尺线条粗细

专业技巧

1. 自适应比例尺:根据地图范围动态计算比例尺长度

def auto_scale(ax):
    xmin, xmax = ax.get_xlim()
    scale_km = round((xmax - xmin) * 0.2 * 110)
    return max(100, round(scale_km, -2))

2. 样式美化:添加背景框增强可读性

# 在比例尺下方添加白色背景
ax.add_patch(plt.Rectangle((x-0.01, y-0.04), 
                          length_km/110 + 0.02, 0.04,
                          transform=transform,
                          facecolor='white', 
                          alpha=0.8))

常见问题解决

  1. 比例尺位置偏移:确保使用transform参数
  2. 比例不准确:PlateCarree投影中1度≈111km
  3. 文字重叠:调整location参数或添加背景

最佳实践:为不同比例的地图设置不同样式的比例尺:

  • 小区域地图:使用500m-5km精细比例尺
  • 国家地图:推荐100-1000km比例尺
  • 全球地图:使用5000km以上比例尺

发表评论