如何在ipython笔记本中使用matplotlib内联时禁用bbox_inches ='tight'

her*_*h10 5 python matplotlib ipython ipython-notebook

在ipython笔记本中使用matplotlib内联后端时,默认行为是使用bbox_inches ='tight'通过savefig()在内部生成嵌入式png图像.这消除了轴周围的空白,并且在大多数情况下都很好.

但是,有时人们可能希望(暂时)禁用此功能,例如,当他想手动保持两个数字垂直对齐时(假设我们不想在这里使用子图):

%matplotlib inline
from pylab import *
plot(rand(100))
subplots_adjust(left=0.2) # Has no effect with inline, but works as expected with qt
figure()
plot(rand(100)*10000) # Will result in a larger left margin for this figure...
subplots_adjust(left=0.2)
Run Code Online (Sandbox Code Playgroud)

那么如何禁用这种行为呢?谢谢〜

编辑

为了使这里涉及的问题更加明确(感谢Anzel),由于更多数字将在yticklabels中显示,因此在bbox_inches ='紧密触发的自动布局调整后,左边距会更大(右边距更小) savefig()中的选项,由notebook在内部调用以生成嵌入式png输出.它将有效地截断我故意用subplots_adjust()创建的任何额外空间,这样第二个数字似乎会向右移动,而不是与第一个数字垂直"对齐".

很容易看出我的意思---只需尝试上面的代码片段:)

我之前没有使用子图/子图的原因(参见Anzel的答案的评论)是,在这个特殊情况下,这两个图本身实际上由数十个小子图组成,加上一些额外的格式/标记.将它们合并为一个更大的子图阵列并非易事......

小智 5

这里有一个更全面的答案:Matplotlib和Ipython-notebook:准确显示将要保存的数字

诀窍是关闭bbox_inches='tight'ipython中的设置.暂时做这个有点尴尬,但只是在一个块中运行IPython魔术:%config InlineBackend.print_figure_kwargs = {'bbox_inches':None}

如果要切换回正常方式,轴标签自动永不切割,您可以运行,%config InlineBackend.print_figure_kwargs = {'bbox_inches':'tight'}但必须在执行需要精确边界框的绘图的块之后.


Anz*_*zel 1

您可以使用pyplot.subplots网格顺序对齐绘图,以便图形在笔记本中视觉上对齐(如果这就是您想要的?)

像这样的东西:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np

d1 = np.random.rand(100)
d2 = np.random.rand(100)*10000

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
plt.subplots_adjust(left=0.2)
ax1.plot(d1)
ax2.plot(d2)
Run Code Online (Sandbox Code Playgroud)

更新

由于OP要求使用单独的图而不是子图,这里有一个hacky解决方案。这适用于我的笔记本,有关自定义的更多详细信息可以在此处找到。

import matplotlib.pyplot as plt
import numpy as np

%matplotlib inline

# to override ytick.major.width before any plot
plt.rcParams['ytick.major.pad'] = 20
plt.plot(np.random.rand(100))

# another override to set alignment for the plot 
plt.rcParams['ytick.major.pad'] = 5
plt.figure()
plt.plot(np.random.rand(100)*10000)
Run Code Online (Sandbox Code Playgroud)

情节

# plt.rcdefaults() will reset everything to defaults as the doc says.
Run Code Online (Sandbox Code Playgroud)

这不是最优雅的方式,但它可以按要求工作。