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

匆匆过客 提交于 2019-12-17 09:59:09

问题


Just noticed this nuance when I editing my works.

Previously, the matplotlib would look like this:

x=[1,2,3,4,5]
y=[4,5,5,2,1]
plot(x,y,'-')

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

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.


回答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:

plt.margins(0)

or

ax.margins(0)

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




回答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)])


来源:https://stackoverflow.com/questions/42713208/matplotlib-cancelling-the-offset-of-axis-introduced-in-matplotlib-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!