Matplotlib: cancelling the offset of axis introduced in matplotlib 2.0 [duplicate]

Posted on

Question :

Matplotlib: cancelling the offset of axis introduced in matplotlib 2.0 [duplicate]

Just noticed this nuance when I editing my works.

Previously, the matplotlib would look like this:


enter image description here

But after recent upgrade I believe, the there are offset, which would return like this

enter image description here

It’s a little bit unncessary from what I seen now. I want to know

  1. If this offset is a good practice in data visualization? If so, I’ll leave it as it is.

  2. How to cancel out this offset?

I can manually restore the limit by plt.gca().set_xlim([1, 5]), but that wouldn’t scale if I have another 20 plots. I googled around and didn’t find too much info on this.

Asked By: cqcn1991


Answer #1:

In matplotlib v2.0.x, the default axes margin has changed, from 0 to 0.05, which is the value controlling the whitespace around your data on the axes. See here for more on the reasoning behind this change.

There are several ways to revert to the previous behaviour.

1) To reset margins to 0 for a single Axes instance:




2) To reset margins to 0 for all plots in a script, use rcParams and set this at the top of your script:

plt.rcParams['axes.autolimit_mode'] = 'round_numbers'
plt.rcParams['axes.xmargin'] = 0.
plt.rcParams['axes.ymargin'] = 0.

3) To change the default value for all plots on a machine, modify your the matplotlibrc file to include these lines:

axes.autolimit_mode: round_numbers
axes.xmargin        : 0.
axes.ymargin        : 0.

Note that to use method (1) and truly get the old behaviour, you may also need to set plt.rcParams['axes.autolimit_mode'] = 'round_numbers'.

Answered By: tmdavison

Answer #2:

Guess whether its good practice is a bit of a discussion. It somehow suggest that your plot continues (but you just show a window of it), so if your plot is only defined in this region having an offset would make sense. If it actually continues but you just plot this part, then it’s logical to remove it.

The scalable approach is

 plt.gca().set_xlim([np.min(x), np.max(x)])
Answered By: Roelant

Leave a Reply

Your email address will not be published. Required fields are marked *