180

I'm using matplotlib to plot data (using plot and errorbar functions) from Python. I have to plot a set of totally separate and independent plots, and then adjust their ylim values so they can be easily visually compared.

How can I retrieve the ylim values from each plot, so that I can take the min and max of the lower and upper ylim values, respectively, and adjust the plots so they can be visually compared?

Of course, I could just analyze the data and come up with my own custom ylim values... but I'd like to use matplotlib to do that for me. Any suggestions on how to easily (and efficiently) do this?

Here's my Python function that plots using matplotlib:

import matplotlib.pyplot as plt

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    # axes
    axes = plt.gca()
    axes.set_xlim([-0.5, len(values) - 0.5])
    axes.set_xlabel('My x-axis title')
    axes.set_ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

    # close figure
    plt.close(fig)
arturomp
  • 28,790
  • 10
  • 43
  • 72
synaptik
  • 8,971
  • 16
  • 71
  • 98

7 Answers7

245

Just use axes.get_ylim(), it is very similar to set_ylim. From the docs:

get_ylim()

Get the y-axis range [bottom, top]

Community
  • 1
  • 1
elyase
  • 39,479
  • 12
  • 112
  • 119
55
 ymin, ymax = axes.get_ylim()

If you are using the plt api directly, you can avoid calls to axes altogether:

def myplotfunction(title, values, errors, plot_file_name):

    # plot errorbars
    indices = range(0, len(values))
    fig = plt.figure()
    plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')

    plt.ylim([-0.5, len(values) - 0.5])
    plt.xlabel('My x-axis title')
    plt.ylabel('My y-axis title')

    # title
    plt.title(title)

    # save as file
    plt.savefig(plot_file_name)

   # close figure
    plt.close(fig)
Adam Hughes
  • 14,601
  • 12
  • 83
  • 122
  • Are there advantages to using the plt api directly vs using axes? I see numerous people suggest that using axes is better, but I haven't been able to nail down why. – BigHeadEd Jun 14 '21 at 00:14
  • 2
    Axes is more programatic - so for example you can build a library of functions that take and operate on axes objects. But the `plt` object is more for just doing something quick. So if you're tinkering, `plt` is faster. If you're building a bigger app, axes probably best. This has been my experience anyway. It's overall a weird API to be honest. – Adam Hughes Jun 14 '21 at 14:18
  • 1
    The overall weird API has its roots in MATLAB. Source: https://matplotlib.org/stable/users/history.html – hintze Sep 13 '21 at 04:27
27

Leveraging from the good answers above and assuming you were only using plt as in

import matplotlib.pyplot as plt

then you can get all four plot limits using plt.axis() as in the following example.

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5, 6, 7, 8]  # fake data
y = [1, 2, 3, 4, 3, 2, 5, 6]

plt.plot(x, y, 'k')

xmin, xmax, ymin, ymax = plt.axis()

s = 'xmin = ' + str(round(xmin, 2)) + ', ' + \
    'xmax = ' + str(xmax) + '\n' + \
    'ymin = ' + str(ymin) + ', ' + \
    'ymax = ' + str(ymax) + ' '

plt.annotate(s, (1, 5))

plt.show()

The above code should produce the following output plot. enter image description here

Thom Ives
  • 3,642
  • 3
  • 30
  • 29
7

Just use plt.ylim(), it can be used to set or get the min and max limit

ymin, ymax = plt.ylim()
Gabriel Cia
  • 388
  • 5
  • 13
  • 1
    Warning: if you use axes, this solution will always return ymin=0, ymax=1. Prefer in this case ymin, ymax = axes.get_ylim() – sol Feb 02 '22 at 08:19
3

I put above-mentioned methods together using ax instead of plt

import numpy as np
import matplotlib.pyplot as plt

x = range(100)
y = x

fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.plot(x, y);

# method 1
print(ax.get_xlim())
print(ax.get_xlim())
# method 2
print(ax.axis())

enter image description here

Jiadong
  • 1,822
  • 1
  • 17
  • 37
0

It's an old question, but I don't see mentioned that, depending on the details, the sharey option may be able to do all of this for you, instead of digging up axis limits, margins, etc. There's a demo in the docs that shows how to use sharex, but the same can be done with y-axes.

Jim
  • 474
  • 5
  • 17
0

Wihout defining axes:

min_lim, max_lim = plt.xlim()
aVral
  • 65
  • 1
  • 9