更改热图的单元格大小

Change the cell size of Heatmap

我用下面的代码绘制了一个热图,它包含 6 列和 40 行,所以当我绘制热图时,它看起来像一个窄柱形图:

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
    
data = pd.read_csv('X.csv')
x = data.drop(['P'],1)
y = data['P']
Performance_Indices = y.to_list()

Columns= ["AMSR1", "AMSR2", "AMSR3",
           "SMAPL3", "SMAPL4", "GLDAS"]

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

    if not ax:
        ax = plt.gca()

    im = ax.imshow(data, **kwargs)
    cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
    cbar.ax.set_ylabel(cbarlabel, rotation=90, va="bottom", fontsize=10,
                       fontweight="bold", labelpad=20)
    ax.set_xticks(np.arange(data.shape[1]))
    ax.set_yticks(np.arange(data.shape[0]))
    ax.set_xticklabels(col_labels, fontsize=10, fontweight="bold")
    ax.set_yticklabels(row_labels, fontsize=10, fontweight="bold")
    ax.tick_params(top=False, bottom=True,
                   labeltop=False, labelbottom=True)
    plt.setp(ax.get_xticklabels(), rotation=90, ha="right",
             rotation_mode="anchor")
    for edge, spine in ax.spines.items():
        spine.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)

    return im, cbar


def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
                     textcolors=["black", "white"],
                     threshold=None, **textkw):
    if not isinstance(data, (list, np.ndarray)):
        data = im.get_array()

    if threshold is not None:
        threshold = im.norm(threshold)
    else:
        threshold = im.norm(data.max())/2.

    kw = dict(horizontalalignment="center",
              verticalalignment="center")
    kw.update(textkw)

    if isinstance(valfmt, str):
        valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)

    texts = []
    for i in range(data.shape[0]):
        for j in range(data.shape[1]):
            kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])
            text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)
            texts.append(text)

    return texts
    
fig, ax = plt.subplots()
im, cbar = heatmap(x, Performance_Indices, farmers, ax=ax,
                   cmap="jet", cbarlabel="Normalized Value")

ax.set_xlabel('Predictive models', fontsize=15, fontweight="bold", labelpad=10)
ax.set_ylabel('Performance Index', fontsize=15, fontweight="bold", labelpad=10)

ax.set_title("b)", fontweight="bold", pad=20, fontsize=15)

但是下图是这样的:

如何调整单元格大小,使单元格可以更大,可以显示小数,并且情节看起来不错!!

由于我没有你的数据所以无法运行你的代码。我刚刚写了以下内容应该可以解决您的问题:

import numpy as np
import matplotlib.pyplot as plt

img = np.random.randint(0,10,(100,100))
# here you can set the figure size
fig,ax = plt.subplots(figsize=(20,20))
# plot somehting - here an image
ax.imshow(img,origin='lower')
# here you can set the aspect ratio
ax.set_aspect(aspect=0.5)
plt.show()