Cómo configurar 'automático' para el límite superior, pero mantener un límite inferior fijo con matplotlib.pyplot


112

Quiero establecer el límite superior del eje y en 'automático', pero quiero mantener el límite inferior del eje y siempre en cero. Intenté 'auto' y 'autorange', pero parece que no funcionan. Gracias de antemano.

Aquí está mi código:

import matplotlib.pyplot as plt

def plot(results_plt,title,filename):

    ############################
    # Plot results

    # mirror result table such that each parameter forms an own data array
    plt.cla()
    #print results_plt
    XY_results = []

    XY_results = zip( *results_plt)

    plt.plot(XY_results[0], XY_results[2], marker = ".")

    plt.title('%s' % (title) )
    plt.xlabel('Input Voltage [V]')
    plt.ylabel('Input Current [mA]')

    plt.grid(True)
    plt.xlim(3.0, 4.2)  #***I want to keep these values fixed"
    plt.ylim([0, 80]) #****CHANGE**** I want to change '80' to auto, but still keep 0 as the lower limit 
    plt.savefig(path+filename+'.png')

Respuestas:


104

Puedes pasar solo lefto rightpara set_xlim:

plt.gca().set_xlim(left=0)

Para el eje y, use bottomo top:

plt.gca().set_ylim(bottom=0)

1
Recibí un error cuando pasé por la izquierda para set_ylim. Usé esto en su lugar: plt.gca (). Set_ylim (ymin = 0) Gracias por su ayuda.
— vietnastee

También puede utilizar plt.xlimo plt.ylimpara establecer los límites del eje actual.
— Chris

26
Cuando hago esto, el límite superior se adhiere al valor en el que la ventana crea una instancia. No permanece en escala automática.
— Elliot

8
El mismo problema que @Elliot aquí. Se puede corregir configurando ylim / xlim (unilateral) después de graficar los valores.
— fabianfuchs

5
Asegúrese de establecer el límite después de graficar los datos, o el límite superior será predeterminado en 1.
— Banana

37

Solo establezca xlimuno de los límites:

plt.xlim(xmin=0)

5
xminy xmaxhan quedado obsoletos a favor lefty righten Matplotlib 3.0.
— onewhaleid

12

Como se mencionó anteriormente y de acuerdo con la documentación de matplotlib, los límites x de un eje dado axse pueden establecer usando el set_xlimmétodo de la matplotlib.axes.Axesclase.

Por ejemplo,

>>> ax.set_xlim(left_limit, right_limit)
>>> ax.set_xlim((left_limit, right_limit))
>>> ax.set_xlim(left=left_limit, right=right_limit)

Un límite puede dejarse sin cambios (por ejemplo, el límite izquierdo):

>>> ax.set_xlim((None, right_limit))
>>> ax.set_xlim(None, right_limit)
>>> ax.set_xlim(left=None, right=right_limit)
>>> ax.set_xlim(right=right_limit)

Para establecer los límites x del eje actual, el matplotlib.pyplotmódulo contiene la xlimfunción que simplemente envuelve matplotlib.pyplot.gcay matplotlib.axes.Axes.set_xlim.

def xlim(*args, **kwargs):
    ax = gca()
    if not args and not kwargs:
        return ax.get_xlim()
    ret = ax.set_xlim(*args, **kwargs)
    return ret

De manera similar, para los límites y, use matplotlib.axes.Axes.set_ylimo matplotlib.pyplot.ylim. Los argumentos de la palabra clave son topy bottom.


3

Simplemente agregue un punto en @silvio: si usa axis para trazar como figure, ax1 = plt.subplots(1,2,1). ¡Entonces ax1.set_xlim(xmin = 0)también funciona!

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.