Matplotlib 带注释的热图格式

Matplotlib annotated heatmaps formatting

我计算了 lat/lon 个箱子的样本数:

dlon = [4.90148783 4.91438189 4.92727594 4.94017    4.95306406 4.96595812] # longitudes
dlat = [51.81923676 51.82162018 51.8240036  51.82638702 51.82877045 51.83115387] # latitudes
count = [[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.]] # number of times a variable is within the gridcell

我通过以下方式创建了带注释的热图:

fig =  plt.figure()
ax = fig.add_subplot(111)
# Show all ticks...
ax.set_xticks(np.arange(len(dlon)))
ax.set_yticks(np.arange(len(dlat)))
# .Label them with the respective entries
ax.set_xticklabels(np.around(dlon, decimals=4))
ax.set_yticklabels(np.around(dlat, decimals=4))
im = ax.imshow(count)
cbar = fig.colorbar(im)

for i in np.arange(np.shape(count)[0]): # over all rows of count 
    for j in np.arange(np.shape(count)[1]): # over all cols of count 
        text = ax.text(j, i, count[i, j],ha="center", va="center" ,color="w")

ax.set_title("Counts in bins")
plt.show()

我有两个问题:1) 在热图中,y 轴上的纬度顺序相反。如何翻转它们,使最大值位于左上角? 2) 我有一个 5x5 的网格(5 行和 5 列),lat/lon 的边界是 6x6。现在它显示了我的网格点的中间,但我想显示网格的角。我该怎么做?

imshow(..., origin='lower') 将原点设置在左下方。请注意,图像通常从顶部开始,因此如果您需要更类似于 xy 图的东西,则必须明确设置原点。

刻度线的轴指向 'pixels' 的中心 0,1,2。如果要标记 'pixels' 之间的边缘,可以使用位置 -0.5、0.5、1.5、...

import matplotlib.pyplot as plt
import numpy as np

dlon = np.array([4.90148783, 4.91438189, 4.92727594, 4.94017, 4.95306406, 4.96595812])  # longitudes
dlat = np.array([51.81923676, 51.82162018, 51.8240036, 51.82638702, 51.82877045, 51.83115387])  # latitudes
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.]])  # number of times a variable is within the gridcell
fig = plt.figure()
ax = fig.add_subplot(111)
# Show all ticks...
ax.set_xticks(np.arange(len(dlon)) - 0.5)
ax.set_yticks(np.arange(len(dlat)) - 0.5)
# .Label them with the respective entries
ax.set_xticklabels(np.around(dlon, decimals=4))
ax.set_yticklabels(np.around(dlat, decimals=4))
im = ax.imshow(count, origin='lower', cmap='plasma')
cbar = fig.colorbar(im)
for i in np.arange(np.shape(count)[0]):  # over all rows of count
    for j in np.arange(np.shape(count)[1]):  # over all cols of count
        text = ax.text(j, i, int(count[i, j]), ha="center", va="center", color="w")
ax.set_title("Counts in bins")
plt.show()