[Python] Setting axis limits in matplotlib pyplot

Discussão em 'Python' iniciado por Stack, Julho 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have two subplots in a figure. I want to set the axes of the second subplot such that it has the same limits as the first subplot (which changes depending on the values plotted).

    import matplotlib.pyplot as plt

    plt.figure(1, figsize=(10, 20))

    ## First subplot: Mean value in each period (mean over replications)
    plt.subplot(211, axisbg='w')
    plt.plot(time,meanVector[0:xMax], color='#340B8C',
    marker='x', ms=4, mec='#87051B', markevery=(asp, 2 * asp))
    plt.xticks(numpy.arange(0, T + 1, jump), rotation=-45)
    plt.axhline(y = Results[0], color='#299967', ls='--')
    plt.ylabel('Mean Value')
    plt.xlabel('Time')
    plt.grid(True)

    ## Second subplot: moving average for determining warm-up period
    ## (Welch method)

    plt.subplot(212)
    plt.plot(time[0:len(yBarWvector)],yBarWvector, color='#340B8C')
    plt.xticks(numpy.arange(0, T + 1, jump), rotation=-45)
    plt.ylabel('yBarW')
    plt.xlabel('Time')
    plt.xlim((0, T))
    plt.grid(True)


    In the second subplot, what should be the arguments for plt.ylim() function? I tried defining

    ymin, ymax = plt.ylim()


    in the first subplot and then set

    plt.ylim((ymin,ymax))


    in the second subplot. But that did not work, because the returned value ymax is the maximum value taken by the y variable (mean value) in the first subplot and not the upper limit of the y-axis.

    Continue reading...

Compartilhe esta Página