[Python] How to remove padding coming from tick labels from other subplots

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have created a set of heatmaps in a 6x3 subplot grid.

    [​IMG]

    As you can see, I added a shared color bar in the last row that spans over all columns (I used a grid spec to realize this).
    While iterating through the rows and columns, I made sure that the Y tick labels are only rendered for the first column and the X tick labels only for the last row.

    I am already pretty happy with the results, except for one thing:
    Due to the Y tick labels from subplots of the first column, the color bar also starts where the Y tick labels start.
    While this is great for the subplots that contain the actual heatmaps, it is unnecessary for the color bar.
    I would like to remove this padding on the left side and if possible center the color bar in the middle of the last row.

    I tried various approaches like disabling the ticks for the color bar axis using cax.set_yticks(ticks=[]) or removing the margin with cax.set_xmargin(0) but nothing worked so far.

    fig = plt.figure(figsize=(12, 13), layout="constrained")

    def render_heatmaps():
    # Create a figure with multiple subplots
    nrows = (
    len(domain_knowledge["DS1: Automotive"]) + 2
    ) # usually 4 + 2 for infobox and color bar
    ncols = len(domain_knowledge.keys()) # usually 3
    gs = fig.add_gridspec(nrows, ncols) # Adjust the width ratios
    gs.set_height_ratios([0.7, 1, 1, 1, 1, 0.1])

    gs.hspace = 0.07
    gs.wspace = 0.02

    # Render infobox
    ax_text: Axes = fig.add_subplot(gs[0, :])
    render_infobox(ax_text)

    # Create a colorbar based on the min/max values that are in all datasets (contingency matrices for each study object)
    norm = mcolors.Normalize(vmin=np.min(datasets), vmax=np.max(datasets))
    colors = ScalarMappable(norm, cmap="GnBu")

    for row in range(nrows - 2):
    for col in range(ncols):
    axis = fig.add_subplot(gs[row + 1, col])

    # Render the combined heatmap
    sns.heatmap(
    datasets[col * 4 + row],
    annot=True,
    cmap=colors.cmap,
    # only show the y labels on the first column
    yticklabels=(categories_necessity[:nec_range] if col == 0 else False),
    # only show the x labels on the last row
    xticklabels=(
    categories_temporality[:temp_range]
    if row + 1 == nrows - 2
    else False
    ),
    ax=axis,
    cbar=False, # uses a combined colorbar
    )

    axis.tick_params(axis="y", labelrotation=0)
    axis.set_title(label=f"S{col*4+row}")

    # create a combined colorbar
    cax = fig.add_subplot(gs[nrows - 1, :]) # Use all columns for the colorbar
    cax.set_xmargin(0)
    fig.colorbar(
    colors,
    cax=cax,
    orientation="horizontal",
    )
    cax.set_title("Number of Study Responses")

    Continue reading...

Compartilhe esta Página