Matplotlib注释的热图格式

时间:2020-02-28 14:52:28

标签: python matplotlib annotations heatmap

我已经统计了经/纬度垃圾箱的样本:

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个列),纬度/经度的边界为6x6。现在它显示了网格点的中间,但是我想显示网格的角。我该怎么做?

1 个答案:

答案 0 :(得分:1)

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

刻度线的“像素”中心的轴线为0,1,2。如果要标记“像素”之间的边缘,则可以使用-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()

resulting plot