[Python] Matplotlib issue with colorbar using subplot_mosaic and make_axes_locatable

Discussão em 'Python' iniciado por Stack, Maio 25, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a figure using subplot_mosaic which is very useful to organize plots. However with my code, when I plot the figure, I don't see the colorbar value and title. This is probably due to make_axes_locatable and constrained_layout=True, but in my case I don't have the choice to use it.

    Moreover, when I save it, I get the entire plot but the aspect ratio is not preserved (5,7).

    This is my code:

    import matplotlib.pyplot as plt
    import numpy as np
    from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable


    def plot2d(data, ax):
    im = ax.imshow(data, aspect="auto")

    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(im, cax=cax, label="DATA")


    fig = plt.figure(constrained_layout=True)
    fig.set_size_inches(5, 7)
    ax = fig.subplot_mosaic([["D1"]])

    plot2d(np.random.rand(10, 1000), ax["D1"])
    plt.savefig("foo3.pdf", bbox_inches="tight", dpi=100)

    plt.show()

    Continue reading...

Compartilhe esta Página