本文将介绍通过Python绘制地形图的方法,所需第三方Python相关模块包括 rasterio、geopandas、cartopy 等,可通过 pip 等方式安装。
1 示例代码
1.1 导入相关模块
| import rasterio |
| import geopandas as gpd |
| import numpy as np |
| import cartopy.crs as ccrs |
| import matplotlib.pyplot as plt |
| from matplotlib.colors import LinearSegmentedColormap |
1.2 设置地图字体及字号
| plt.rcParams["font.family"] = "Times New Roman" |
| plt.rcParams["font.size"] = 14 |
1.3 绘制地图
| # 设置投影:墨卡托投影 |
| # cartopy 投影说明:https://www.cnblogs.com/youxiaogang/p/14247184.html |
| projection = ccrs.Mercator() |
|
|
| # 绘制地图 |
| fig, ax = plt.subplots(figsize=(20, 10), subplot_kw={'projection': projection}) |
|
|
| # 设置地图范围(数值参数为对应投影下的范围坐标) |
| ax.set_extent([13530000, 14630000, 4960000, 5850000], crs=projection) |
|
|
| # 读取矢量文件 |
| shp = gpd.read_file("Data/Jilin_Mercator.shp") |
| shp.plot(ax=ax, transform=projection, edgecolor="black", linewidth=1, facecolor="none") |
|
|
| # 创建自定义颜色映射 |
| colors = ["#369121", "#95C769", "#FFFFBF", "#E6865A", "#D14E30", "#BA1414"] |
| n_bins = 100 # 定义色带的颜色数量 |
| cmap_name = "green_brown" |
| cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=n_bins) |
|
|
| # 读取地形栅格数据 |
| dataset = rasterio.open("Data/DEM_Jilin_Mercator.tif") |
| data = dataset.read(1) # 读取第一个波段的数据 |
| nodata_value = dataset.nodata # 获取NoData值 |
| # 创建掩膜,去除NoData区域 |
| data = np.ma.masked_where(data == nodata_value, data) |
|
|
| # 将地形栅格添加到地图中 |
| extent = [dataset.bounds.left, dataset.bounds.right, |
| dataset.bounds.bottom, dataset.bounds.top] |
| im = ax.imshow(data, origin="upper", extent=extent, |
| transform=projection, cmap=cm) |
|
|
| # 绘制网格线并添加标签 |
| gl = ax.gridlines(draw_labels=True, linestyle="--", color="#4F4F4F") |
| gl.xlocator = plt.FixedLocator(range(120, 135, 3)) |
| gl.ylocator = plt.FixedLocator(range(40, 50, 2)) |
|
|
| # 添加色带,设置色带的缩放比例为 0.4,主图和色带之间的间距为 0.1 |
| cbar = plt.colorbar(im, ax=ax, orientation="horizontal", shrink=0.4, pad=0.1) |
| cbar.set_label("Elevation (m)", labelpad=10) # 设置色带标签与色带的距离为 10 点 |
| cbar.ax.xaxis.set_label_position("top") # 设置色带标签位置 |
|
|
| plt.savefig("Pic.jpg", dpi=600) |
| plt.show() |
2 结果图展示
链接:https://www.cnblogs.com/qsgeo/p/18030978
(版权归原作者所有,侵删)