Matplotlib rcparams (autolimit_mode) for single figure

匿名 (未验证) 提交于 2019-12-03 01:08:02

问题:

I have an issue with the new Matplotlib 2.0.0.

The new autolimit_mode value by default add a padding to the frame. I want to avoid it to a single figure.

If I change rcParams, the changes affect to any generated figures.

Can I change this parameter for a single figure without affect the behavior of the rest?


Update

I update the question with some code and the different results obtained.

import numpy as np import matplotlib import matplotlib.pyplot as plt   def remove_frame_border(ax):     ax.spines['top'].set_visible(False)     ax.spines['right'].set_visible(False)     ax.spines['left'].set_visible(False)     ax.spines['bottom'].set_visible(False)   def draw1(xserie, yserie):     fig = plt.figure(figsize=(8,3))     ax = fig.add_subplot(111)      ax.plot(xserie, yserie)     ax.grid(True)     remove_frame_border(ax)      fig.savefig('out1.png', format='png', bbox_inches='tight', pad_inches=0)   def draw2(xserie, yserie):     fig = plt.figure(figsize=(8,3))     ax = fig.add_subplot(111)      # Fixed autolimit padding in matplotlib 2.0.0     ax.set_xmargin(0)     ax.set_ymargin(0)     ax.autoscale_view()      ax.plot(xserie, yserie)     ax.grid(True)     remove_frame_border(ax)      # Restore default matplotlib params     matplotlib.rcParams.update(matplotlib.rcParamsDefault)      fig.savefig('out2.png', format='png', bbox_inches='tight', pad_inches=0)   def draw3(xserie, yserie):     # Fixed autolimit padding in matplotlib 2.0.0     matplotlib.rcParams['axes.autolimit_mode'] = 'round_numbers'     matplotlib.rcParams['axes.xmargin'] = 0     matplotlib.rcParams['axes.ymargin'] = 0      fig = plt.figure(figsize=(8,3))     ax = fig.add_subplot(111)      ax.plot(xserie, yserie)     ax.grid(True)     remove_frame_border(ax)      # Restore default matplotlib params     matplotlib.rcParams.update(matplotlib.rcParamsDefault)      fig.savefig('out3.png', format='png', bbox_inches='tight', pad_inches=0)    xserie = np.array([1,2,3,4,5,6,7,8,9,10]) yserie = np.array([0, 22.2, 33.4, 55.6, 66.6, 77.7, 100.3, 123.3, 90.4, 93.3])  draw1(xserie, yserie) draw2(xserie, yserie) draw3(xserie, yserie) 
  • draw1 is the default behavior
  • draw2 call ax.set_xmargin and ax.set_ymargin
  • draw3 change the rcParams and restore it after generate the chart

out1.png

out2.png

out3.png

回答1:

Matplotlib provides the method matplotlib.axes.Axes.set_xmargin:

Set padding of X data limits prior to autoscaling. m times the data interval will be added to each end of that interval before it is used in autoscaling.

So setting

ax.set_xmargin(0)  

removes the padding.

However it seems for this to have an effect, one also needs to call matplotlib.axes.Axes.autoscale_view

ax.autoscale_view()  

I did not entirely understand the docstring of autoscale_view but the combination here seems to work.



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