Search code examples
matplotlibplotheatmap

Change the cell size of Heatmap


I'm plotting a Heatmap with the code bellow. It contains 6 columns and 40 rows so when I plot the heatmap its looks like a narrow column figure:

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)

enter image description here

How can the cell size be increased so that decimal number show?


Solution

  • Since I do not have your data and therefore can not run your code. I just wrote the following which should solve your problem:

    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()