[Python] How to give same space for y axis tick labels in Matplotlib for different figures?

Discussão em 'Python' iniciado por Stack, Agosto 29, 2025.

  1. Stack

    Stack Membro Participativo

    I need to plot figures using the same function.

    Yaxis tick labels can be 2 digit and sometimes 3 digit integer numbers.

    Although I format the y axis tick labels as 3 digit integers, spacing before the left spine slightly changes.

    How to give same space for the y axis tick labels so that the left spine of the axis starts at the same location for different figures?

    Here is the sample code to replicate these figures:

    from matplotlib import pyplot as plt
    from matplotlib.ticker import FormatStrFormatter
    from matplotlib.ticker import MaxNLocator

    import numpy as np
    import os

    def plot_figure(start, end, figure_name):
    fwidth = 15
    fheight = 7

    fig = plt.figure(figsize=(fwidth, fheight), facecolor=None)
    plt.style.use('ggplot')

    # define margins
    left_margin = 0.95 / fwidth
    right_margin = 0.2 / fwidth
    bottom_margin = 0.5 / fheight
    top_margin = 0.25 / fheight

    # create axes
    x = left_margin # horiz. position of bottom-left corner
    y = bottom_margin # vert. position of bottom-left corner
    w = 1 - (left_margin + right_margin) # width of axes
    h = 1 - (bottom_margin + top_margin) # height of axes
    ax = fig.add_axes([x, y, w, h])

    ax.set_facecolor('white')

    # This code puts the edge line
    for edge_i in ['left', 'bottom','right', 'top']:
    ax.spines[edge_i].set_edgecolor("black")
    ax.spines[edge_i].set_linewidth(3)

    plus_minus = 50
    x = np.arange(-plus_minus, plus_minus + 1, 1)
    signal_array = np.random.randint(start, end + 1, size = 2*plus_minus+1)
    plt.plot(x, signal_array, color='b', label='Signal', linewidth=2, zorder=10)

    # This code puts the tick marks
    plt.tick_params(axis='both', which='major', labelsize=50, width=3, length=10)
    plt.tick_params(axis='both', which='minor', labelsize=50, width=3, length=10)

    # This code provides the x and y tick marks and labels
    plt.xticks(np.arange(-plus_minus/2, plus_minus/2+1, step=plus_minus/2), fontsize=50)
    plt.xlim((-plus_minus, plus_minus))

    ax.yaxis.set_major_formatter(FormatStrFormatter('%3d'))
    ax.yaxis.set_major_locator(MaxNLocator(integer=True, min_n_ticks=3, nbins=2))
    ax.yaxis.set_major_locator(MaxNLocator(3))

    figure_file = os.path.join('/Users','burcakotlu','Desktop','test2.png')
    fig.savefig(figure_file, dpi=100, bbox_inches="tight")
    plt.close(fig)

    plot_figure(20, 50, 'test1')
    plot_figure(100, 130, 'test2')


    [​IMG] [​IMG]

    Continue reading...

Compartilhe esta Página