Python | 基于栅格数据绘制空间分布图

职场   2024-12-30 00:17   陕西  
一、Python代码
该代码的流程包括读取栅格数据、去除异常值、基于数据的地理范围生成经纬度网格,并使用Cartopy在平面投影下绘制全球范围的地图,添加海岸线和经纬度刻度。接着,通过contourf函数绘制等值线图,展示数据的空间分布,并采用'RdYlGn'颜色映射来呈现数据的值变化。
同学们可以根据自身需求更改栅格数据的路径、有效值范围、图标题和图例等设置。
import matplotlibmatplotlib.use('TkAgg')import numpy as npimport rasterioimport matplotlib.pyplot as pltimport cartopy.crs as ccrsimport cartopy.feature as cfeaturefrom cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatterfrom shapely.geometry import box
# 配置字体为 Arialplt.rcParams['font.sans-serif'] = ['Arial'] # 设置为Arialplt.rcParams['axes.unicode_minus'] = False
# 栅格数据路径tif_path = r"E:\GLASS\GLASS_AVHRR_GPP_YEAR\GPP_SEN_TREND.tif"
with rasterio.open(tif_path) as src: data = src.read(1) # 读取第一个波段数据 lon_min, lat_min, lon_max, lat_max = src.bounds # 获取地理范围 transform = src.transform # 获取仿射变换参数
data = np.flipud(data)data[data > 50] = np.nandata[data < -50] = np.nan
# 检查数据范围print(f"数据范围:最小值={np.nanmin(data)}, 最大值={np.nanmax(data)}")
# 生成经纬度网格lon = np.linspace(lon_min, lon_max, data.shape[1])lat = np.linspace(lat_min, lat_max, data.shape[0])lon, lat = np.meshgrid(lon, lat)
# 验证边界框有效性bounds = box(lon_min, lat_min, lon_max, lat_max)if not bounds.is_valid: raise ValueError("Bounding box is invalid.")
# 绘图函数def plot_raster(): fig = plt.figure(figsize=(10, 6)) ax = fig.add_subplot(111, projection=ccrs.PlateCarree()) ax.set_title('Title', loc='left', fontsize=16) ax.add_feature(cfeature.COASTLINE.with_scale('110m'), linewidth=0.8) ax.set_xticks(np.arange(-180, 181, 60), crs=ccrs.PlateCarree()) ax.set_yticks(np.arange(-90, 91, 30), crs=ccrs.PlateCarree()) ax.xaxis.set_major_formatter(LongitudeFormatter()) ax.yaxis.set_major_formatter(LatitudeFormatter()) ax.tick_params(labelsize=10)
# 绘制等值线图 try: levels = [-20, -15, -10, -5, 0, 5, 10, 15, 20] contour = ax.contourf(lon, lat, data, levels=levels, cmap='RdYlGn', extend='both', transform=ccrs.PlateCarree()) except Exception as e: print(f"Error in contourf: {e}") raise
cbar = plt.colorbar(contour, ax=ax, orientation='horizontal', pad=0.07, aspect=55, format='%.0f') cbar.set_label('Legend', fontsize=18) cbar.ax.tick_params(labelsize=14) cbar.set_ticks([-20, -15, -10, -5, 0, 5, 10, 15, 20]) #plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.savefig(r'E:\PML_ET_GPP\PML_WUE等\出图\Summer average of t_et.jpg', dpi=300, bbox_inches='tight', pad_inches=0) plt.show()
plot_raster()
二、成为会员

GIS遥感数据处理应用
会员:数据处理,ArcGIS/Python/MATLAB/R/GEE教学,指导作图和论文。
 最新文章