Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot

People also ask

What are the two ways to adjust axis limits of the plot using matplotlib?

Adjust axis limits: To set the limits of x and y axes, we use the commands plt. xlim() and plt. ylim().

How do I limit a range in matplotlib?

Import matplotlib. To set x-axis scale to log, use xscale() function and pass log to it. To plot the graph, use plot() function. To set the limits of the x-axis, use xlim() function and pass max and min value to it. To set the limits of the y-axis, use ylim() function and pass top and bottom value to it.


You can pass just left or right to set_xlim:

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

For the y axis, use bottom or top:

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

Just set xlim for one of the limits:

plt.xlim(left=0)

As aforementioned and according to the matplotlib documentation, the x-limits of a given axis ax can be set using the set_xlim method of the matplotlib.axes.Axes class.

For instance,

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

One limit may be left unchanged (e.g. the left limit):

>>> 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)

To set the x-limits of the current axis, the matplotlib.pyplot module contains the xlim function that just wraps matplotlib.pyplot.gca and 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

Similarly, for the y-limits, use matplotlib.axes.Axes.set_ylim or matplotlib.pyplot.ylim. The keyword arguments are top and bottom.


Just add a point on @silvio 's: if you use axis to plot like figure, ax1 = plt.subplots(1,2,1). Then ax1.set_xlim(xmin = 0) also works!


You can also do:

ax.set_xlim((None,upper_limit))
ax.set_xlim((lower_limit,None))

That is helpful if you want to use set(), which allows you to set several parameters at once:

ax.set(xlim=(None, 3e9), title='my_title', xlabel='my_x_label', ylabel='my_ylabel')

The set_xlim and set_ylim permit None values to achieve this. However, you must use the functions AFTER you have plotted the data. If you don't do this, it will use the default 0 for left/bottom and 1 for top/right. It does not recalculate the "automatic" limit each time you plot new data once you have set the limits.

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0, 1, 4, 5], [3, 5, 6, 9])
ax.set_xlim(left=2, right=None)
ax.set_ylim(bottom=None, top=7)

plt.show()

(I.e., in the above example, if you would do ax.plot(...) at the end, it won't give the desired effect.)