Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.pyplot - fix only one axis limit, set other to auto

The following MWE produces a simple scatter plot:

import numpy as np
import matplotlib.pyplot as plt

# Generate some random two-dimensional data:
m1 = np.random.normal(size=100)
m2 = np.random.normal(scale=0.5, size=100)

# Plot data with 1.0 max limit in y.
plt.figure()
# Set x axis limit.
plt.xlim(0., 1.0)
# Plot points.
plt.scatter(m1, m2)
# Show.
plt.show()

In this plot the x axis limits are set to [0., 1.]. I need to set the upper y axis limit to 1. leaving the lower limit to whatever the min value in m2 is (ie: let python decide the lower limit).

In this particular case I could just use plt.ylim(min(m2), 1.0) but my actual code is far more complicated with lots of things being plotted so doing this is not really an option.

I've tried setting:

plt.ylim(top=1.)

and also:

plt.gca().set_ylim(top=1.)

as advised here How to set 'auto' for upper limit, but keep a fixed lower limit with matplotlib.pyplot, but neither command seems to work. They both correctly set the upper limit in the y axis to 1. but they also force a lower limit of 0. which I don't want.

I'm using Python 2.7.3 and Matplotlib 1.2.1.

like image 906
Gabriel Avatar asked Sep 07 '13 17:09

Gabriel


1 Answers

If the concern is simply that a lot of data is being plotted, why not retrieve the plot's lower y-limit and use that when setting the limits?

plt.ylim(plt.ylim()[0], 1.0)

Or analogously for a particular axis. A bit ugly, but I see no reason why it shouldn't work.


The issue actually resides in the fact that setting the limits before plotting disables autoscaling. The limits for both the x and y axes are, by default, (0.0, 1.0), which is why the lower y limit remains at 0.

The solution is simply to set the plot limits after calling all plot commands. Or you can re-enable autoscaling if needed

like image 89
Sajjan Singh Avatar answered Oct 04 '22 14:10

Sajjan Singh