Reputation: 231
If I plot something in matplotlib it chooses the spacing on y-axis by itself (where it puts ticks). How can I tell the axes to always end with an full tick and not in between two ticks?
If it choses to make a tick every 0.5, that the end is 2.0 and not a little bit higher than 2.0 with no tick.
import matplotlib.pyplot as plt
X = [1,2,3,4,5]
y = [0.1,0.3,2.4,3.9,3.2]
plt.plot(X, y)
plt.show()
Upvotes: 5
Views: 4513
Reputation: 39042
Just use plt.xlim
and plt.ylim
if you want to restrict the limits to within some range. Here is an example:
import matplotlib.pyplot as plt
import numpy as np
X = [1,2,3,4,5]
# y = [0.1,0.3,2.4,3.9,3.2]
y = [0.1,0.2,0.3,0.5,1.1]
plt.plot(X, y)
plt.xlim(min(X), max(X))
ticks = [tick for tick in ax.get_yticks()]
plt.ylim(ticks[0], ticks[-1])
# plt.ylim(np.floor(min(y)), np.ceil(max(y))) # If you want only integer upper and lower limits
EDIT: This addresses your concern for the following set of values X = [1,2,3,4,5]
and y = [0.1,0.2,0.3,0.5,1.1]
Upvotes: 1
Reputation: 339052
By default you will get the axes autoscaled to extend by some percentage of the range of the data.
So the tick locations and the axis limits are totally uncorrelated. This mostly gives a nice visual appearance of the chart content.
You may however decide to activate the round number autolimit mode,
plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
to have the limits and ticks correlate:
Here, a lot of whitespace is created around the plotted data. You may decide to set the margins to 0
to aviod that
plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0
plt.rcParams['axes.ymargin'] = 0
Note that this mode will in general expand to the next "nice number", which may, or may not be desired. E.g. if you let the first x value be a bit smaller than 1, X = [0.99,2,3,4,5]
the limits will expand down to 0.5
There is also an example available on the matplotlib page.
Upvotes: 5
Reputation: 25363
The newer versions of matplotlib now add margins to your plot by default. You can remove them by calling plt.margins(0, 0)
:
import matplotlib.pyplot as plt
X = [1,2,3,4,5]
y = [0.1,0.3,2.4,3.9,3.2]
plt.plot(X, y)
plt.margins(0, 0)
plt.show()
This does however generate the axes limts automatically. In the above example, this will not include 0 or 4 (because the data does not include 0 or 4). Therefore, you can set the axes limits yourself:
plt.ylim(0, 4)
Upvotes: 1