Matplotlib标注热力图格式调整:坐标轴与网格边界问题
问题2:将刻度从网格中点改为显示网格角落(边界)
你的count是5×5的网格数据,而dlon/dlat是6×6的网格边界点——每个count[i][j]对应dlon[j]~dlon[j+1]、dlat[i]~dlat[i+1]的区域。要让刻度落在这些边界上,需要用extent参数定义实际坐标范围,同时调整刻度位置:
修改后的完整代码片段
import matplotlib.pyplot as plt import numpy as np # 你的原始数据 dlon = np.array([4.90148783, 4.91438189, 4.92727594, 4.94017, 4.95306406, 4.96595812]) dlat = np.array([51.81923676, 51.82162018, 51.8240036, 51.82638702, 51.82877045, 51.83115387]) count = np.array([[10., 16., 16., 0., 5.], [0., 0., 0., 5., 0.], [0., 0., 0., 0., 2.], [0., 0., 0., 2., 0.], [12., 0., 6., 13., 13.]]) fig = plt.figure() ax = fig.add_subplot(111) # 定义坐标范围:[经度最小值, 经度最大值, 纬度最大值, 纬度最小值] # 因为origin='upper',所以top是最大纬度,bottom是最小纬度 extent = [dlon.min(), dlon.max(), dlat.max(), dlat.min()] # 绘制热力图,绑定坐标范围与原点位置 im = ax.imshow(count, origin='upper', extent=extent) # 将刻度设置为经纬度的边界点 ax.set_xticks(dlon) ax.set_yticks(dlat[::-1]) # 反转纬度列表,让最大值在最上方 # 格式化刻度:保留4位小数,关闭科学计数法偏移 ax.ticklabel_format(useOffset=False) plt.xticks(rotation=45) # 可选:旋转经度标签避免重叠 # 添加颜色条 cbar = fig.colorbar(im) # 在每个网格中心添加计数标注 for i in range(count.shape[0]): for j in range(count.shape[1]): # 通过边界点计算网格中心的经纬度坐标 lon_center = (dlon[j] + dlon[j+1]) / 2 lat_center = (dlat[i] + dlat[i+1]) / 2 ax.text(lon_center, lat_center, int(count[i][j]), ha="center", va="center", color="white") ax.set_title("Counts in bins") plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
关键说明:
extent参数直接关联了热力图像素和实际地理坐标,让刻度自动对齐到网格边界;- 文本标注的位置需要通过边界点计算网格中心,而不是用原来的行/列索引;
ticklabel_format(useOffset=False)可以防止matplotlib用科学计数法显示经纬度,保证可读性。
内容的提问来源于stack exchange,提问作者Jeroen
相关产品推荐
相关产品推荐

