热图中不需要的空间

Unwanted spaces in heat map

你好我想用热图来显示一段时间内降水中氘的变化。为此,我使用了以下代码: (来源:https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html#sphx-glr-gallery-images-contours-and-fields-image-annotated-heatmap-py

import numpy as np
import matplotlib
import matplotlib.pyplot as plt

Jahre = ["1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005", "2006", "2007",          ]
Monate = ["Jannuar", "Feburar", "März", "April", "Mai", "Juni", "Julie", "August", "September", "Oktober", "November",
          "Dezember"]

Deuterium = np.array([[-90, -62.3, -53.8, -89.7, -44.2, -43.9, -46.6, -48.5, -61.3, -69.9, -98.1, -64.3],
              [-87.5, -63.1, -78.5, -66.4, -38.6, -41.5, -45.5, -54.3, -51, -40.2, -76.6, -58.1],
              [-61.9, -63.3, -64.3, -60.5, -38, -26.1, -57.6, -35.6, -61.9, -50.9, -75, -87.5],
              [-102, -71.2, -85.8, -72.4, -34.7, -53, -42.7, -31.6, -63.9, -50.1, -81.5, -79.6],
              [-69.6, -64.6, -74.8, -86.9, -36.8, -27.3, -38.3, -52.7, -51.1, -70.1, -90.7, -119.1],
              [-82.5,-99.9,-82.6,-72.9,-36.5,-26.8,-44,-19.2,-51.4,-58.8,-77.5,-88.9],
              [-100.3,-71.1,-56.4,-53.8,-56.1,-31.9,-45.3,-44.8,-36.9,-41.9,-73.2,-76.3],
              [-58.1,-124.9,-75.2,-58.3,-57.2,-47.5,-52.9,-52.5,-47.1,-86.1,-80,-83.7],
              [-95.5,-87.4,-102.1,-48.9,-75.8,-32.2,-13.1,-67.8,-25.3,-51.1,-35.5,-81.6],
              [-69.7,-88.3,-68.4,-18.5,-47.9,-42,-46,-44.7,-53.2,-48,-69.6,-78]])

fig, ax = plt.subplots()
im = ax.imshow(Deuterium)

# Show all ticks and label them with the respective list entries
ax.set_xticks(np.arange(len(Monate)))
ax.set_xticklabels(labels=Monate)
ax.set_yticks(np.arange(len(Jahre)))
ax.set_yticklabels(labels=Jahre)

# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
         rotation_mode="anchor")


ax.set_title("Deuterium in Precipitation")
fig.tight_layout()
plt.show()

当我激活它时,我在图像中得到了这些空间

如何删除它们?

尝试使用

plt.rcParams["axes.grid"] = False

如果您使用了 link 中的示例(来源:link),您可以评论这些行:

# ax.spines[:].set_visible(False)

# ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
# ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
# ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
# ax.tick_params(which="minor", bottom=False, left=False)

白色网格通过这些线显示

可加参数显示或不显示

def heatmap(data, row_labels, col_labels, ax=None,
        cbar_kw={}, cbarlabel="", grid = False, **kwargs):

    ...
    if grid:
        ax.spines[:].set_visible(False)
    
        ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)
        ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)
        ax.grid(which="minor", color="w", linestyle='-', linewidth=3)
        ax.tick_params(which="minor", bottom=False, left=False)