652

I need help with setting the limits of y-axis on matplotlib. Here is the code that I tried, unsuccessfully.

import matplotlib.pyplot as plt

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
aPlot = plt.subplot(321, axisbg = 'w', title = "Year 1")
ax.append(aPlot)
plt.plot(paramValues,plotDataPrice[0], color = '#340B8C', 
     marker = 'o', ms = 5, mfc = '#EB1717')
plt.xticks(paramValues)
plt.ylabel('Average Price')
plt.xlabel('Mark-up')
plt.grid(True)
plt.ylim((25,250))

With the data I have for this plot, I get y-axis limits of 20 and 200. However, I want the limits to be 20 and 250.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Curious2learn
  • 31,692
  • 43
  • 108
  • 125

9 Answers9

941

Get current axis via plt.gca(), and then set its limits:

ax = plt.gca()
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Hima
  • 11,268
  • 3
  • 22
  • 31
  • 366
    BTW, this is a silly abbreviation means "**g**et the **c**urrent **a**xes". – Lenar Hoyt May 08 '17 at 10:57
  • 88
    you can also set one value `None` which leaves the calculation to matplotlib, e.g. `axes.set_ylim([ymin,None])` – linqu Sep 13 '18 at 10:14
  • 2
    There are other options instead of using `None` as in @linqu 's post: `set_ylim(bottom=None, top=None, [...], *, ymin=None, ymax=None)`. `bottom` and `ymin` (equivalent) for minimum. `top` and `ymax`) equivalent for maximum. You can't use both `bottom` and `ymin` at once. Same with `top` and `ymax`. – MaciekS Nov 04 '21 at 08:24
170

One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.

matplotlib.pyplot.axis

from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])

0,10 is for x axis range. 0,20 is for y axis range.

or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim

matplotlib.pyplot.ylim

plt.ylim(-2, 2)
plt.xlim(0,10)
Birat Bose
  • 1,954
  • 1
  • 9
  • 11
152

Another workaround is to get the plot's axes and reassign changing only the y-values:

x1,x2,y1,y2 = plt.axis()  
plt.axis((x1,x2,25,250))
iacob
  • 20,084
  • 6
  • 92
  • 119
thetarro
  • 1,827
  • 1
  • 10
  • 5
  • 4
    You don't need to grab `x1` and `x2`, you can have matplotlib infer these with `None`. – iacob Mar 24 '21 at 20:35
43

You can instantiate an object from matplotlib.pyplot.axes and call the set_ylim() on it. It would be something like this:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])
mechnicov
  • 12,025
  • 4
  • 33
  • 56
Reza Keshavarz
  • 688
  • 2
  • 9
  • 17
41

Just for fine tuning. If you want to set only one of the boundaries of the axis and let the other boundary unchanged, you can choose one or more of the following statements

plt.xlim(right=xmax) #xmax is your value
plt.xlim(left=xmin) #xmin is your value
plt.ylim(top=ymax) #ymax is your value
plt.ylim(bottom=ymin) #ymin is your value

Take a look at the documentation for xlim and for ylim

loved.by.Jesus
  • 2,266
  • 28
  • 34
30

This worked at least in matplotlib version 2.2.2:

plt.axis([None, None, 0, 100])

Probably this is a nice way to set up for example xmin and ymax only, etc.

Antti A
  • 692
  • 5
  • 10
18

To add to @Hima's answer, if you want to modify a current x or y limit you could use the following.

import numpy as np # you probably alredy do this so no extra overhead
fig, axes = plt.subplot()
axes.plot(data[:,0], data[:,1])
xlim = axes.get_xlim()
# example of how to zoomout by a factor of 0.1
factor = 0.1 
new_xlim = (xlim[0] + xlim[1])/2 + np.array((-0.5, 0.5)) * (xlim[1] - xlim[0]) * (1 + factor) 
axes.set_xlim(new_xlim)

I find this particularly useful when I want to zoom out or zoom in just a little from the default plot settings.

Steven C. Howell
  • 16,902
  • 15
  • 72
  • 97
12

This should work. Your code works for me, like for Tamás and Manoj Govindan. It looks like you could try to update Matplotlib. If you can't update Matplotlib (for instance if you have insufficient administrative rights), maybe using a different backend with matplotlib.use() could help.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • Thanks for checking! I am using the pdf backend (`matplotlib.use('PDF')`). I am using the version that comes with latest version of the Enthought Python Distribution. Can you please see if it works with the PDF backend. Thanks! – Curious2learn Sep 23 '10 at 12:25
  • It does work with the PDF backend, on Mac OS X. Are you sure that the output file is indeed updated with `plt.savefig()`? – Eric O. Lebigot Sep 23 '10 at 13:43
  • I realized the problem, I think. If I take out `aPlot =` in the `plt.subplot` line it works for me too. It seems that if one assigns the subplot to a variable like that, some other method of setting the axes limits must be used. Is that true? – Curious2learn Sep 23 '10 at 13:47
  • 2
    As far as I know, `plt.ylim()` applies the limits to the current axes, which are set when you do `plt.subplot()`. I also can't believe that `plt.subplot()` care about how the axes it returns are used (put into a variable or not, etc.). So I'd say it should work; it does work on my machine. – Eric O. Lebigot Sep 23 '10 at 16:39
0

ylim can be set using Axes.set(). In fact a whole host of properties can be set via set(), such as ticks, ticklabels, labels, title etc. (that were set separately in the OP).

ax = plt.gca()
ax.set(ylim=(20, 250), xlim=(0, 100))

Then again, ylim (and other properties) can be set in the plt.subplot instance as well. For the case in the OP, that would be

aPlot = plt.subplot(321, facecolor='w', title="Year 1", ylim=(20,250), xticks=paramValues, ylabel='Average Price', xlabel='Mark-up')
#                                                       ^^^^  <---- ylim here
plt.plot(paramValues, plotDataPrice[0], color='#340B8C', marker='o', ms=5, mfc='#EB1717');

To set ylim (and other properties) for multiple subplots, use plt.setp. For example, if we include 2 more subplots to OP's code and if we want to set the same properties to all of them, one way to do it would be as follows:

import matplotlib.pyplot as plt
import random

plt.figure(1, figsize = (8.5,11))
plt.suptitle('plot title')
ax = []
paramValues = range(10)
for i in range(1, 4):
    aPlot = plt.subplot(3,2,i, title=f"Year {i}")
    ax.append(aPlot)
    aPlot.plot(paramValues, [random.randint(20,200) for _ in paramValues], color='#340B8C', marker='o', ms=5, mfc='#EB1717')
    aPlot.grid(True);

plt.setp(ax, ylim=(20,250), facecolor='w', xticks=paramValues, ylabel='Average Price', xlabel='Mark-up')
#            ^^^^  <---- ylim here
plt.tight_layout();
cottontail
  • 10,268
  • 18
  • 50
  • 51