Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib: set axis tight only to x or y axis

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.

like image 987
cqcn1991 Avatar asked Jun 01 '16 02:06

cqcn1991


People also ask

How do you scale X and Y axis in Python?

MatPlotLib with Python To change the range of X and Y axes, we can use xlim() and ylim() methods.

How do I change the axis limits in Python?

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.

What does PLT Tight_layout () do?

The tight_layout() function in pyplot module of matplotlib library is used to automatically adjust subplot parameters to give specified padding.


2 Answers

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'.

like image 92
Vadim Shkaberda Avatar answered Oct 10 '22 19:10

Vadim Shkaberda


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.

like image 20
eric Avatar answered Oct 10 '22 21:10

eric