29

I have a plot look like this:

enter image description here

Obviously, the left and right side is a waste of space, so I set

plt.axis('tight')

But this gives me plot like this:

enter image description here

The xlim looks right now, but the ylim is too tight for the plot.

I'm wondering, if I can only set axis(tight) only to x axis in my case?

So the plot may look something like this:

enter image description here

It's certainly possible that I can do this manually by

plt.gca().set_xlim(left=-10, right=360)

But I'm afraid this is not a very elegant solution.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206
  • Still trying to figure out why they have weird behavior as the default here. – eric Aug 20 '20 at 20:49
  • More generally, you may also want to show, e.g., a *subset* of the plotted xrange, and have the yrange be tight for that narrow (in x) view of what was plotted. Or vice versa. The accepted answer can be used for this too, ie. in general to set ytight or xtight independently (to use Matlab terminology)... – CPBL Apr 09 '23 at 15:18

2 Answers2

58

You want to use matplotlib's autoscale method from the matplotlib.axes.Axes class.

enter image description here

Using the functional API, you apply a tight x axis using

plt.autoscale(enable=True, axis='x', tight=True)

or if you are using the object oriented API you would use

ax = plt.gca()  # only to illustrate what `ax` is
ax.autoscale(enable=True, axis='x', tight=True)

enter image description here

For completeness, the axis kwarg can take 'x', 'y', or 'both', where the default is 'both'.

Steven C. Howell
  • 16,902
  • 15
  • 72
  • 97
Vadim Shkaberda
  • 2,807
  • 19
  • 35
2

I just put the following at the beginning of those scripts in which I know I'll want my xlims to hug my data:

import matplotlib.pyplot as plt
plt.rcParams['axes.xmargin'] = 0

If I decide to add some whitespace buffer to an individual plot in that same script, I do it manually with:

plt.xlim(lower_limit, upper_limit)

While the accepted answer works, and is what I used for a while, I switched to this strategy because I only have to remember it once per script.

eric
  • 7,142
  • 12
  • 72
  • 138