Matplotlib:图形左边缘和 y 轴之间的固定间距

ede*_*esz 7 python plot matplotlib python-2.7

我用 Python 2.7 在 Matplotlib 中生成了 2 个图。绘图保存为 *.png 文件。保存后,两个图像具有相同的分辨率 - 宽度 = 1099 像素,高度 = 619 像素。

然而,当我垂直对齐保存的 *.png 图像时(见下图),y 轴和图像最左边点之间的间距并不相同 - 请参见下图中的ab 。在此输入图像描述

我的意思是,从图像左侧到 y 轴的距离不一样(a 不等于 b)。

单击图像放大并查看。

问题: 有没有办法强制 y 轴从相对于图像左侧的特定位置开始?

注意:我不关心刻度标签和轴标签之间的空间 - 我可以使用类似的东西来调整它ax.yaxis.labelpad(25)。但是,我不知道如何修复图像左侧和 y 轴之间的空间。

注 2:我使用以下方法创建绘图:

fig = plt.figure(1)
ax = fig.add_subplot(111)
fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)

Jea*_*ien 7

如果我想精细控制 matplotlib 中图形边距的大小,这就是我通常设置代码的方式。此外,我还展示了如何设置 ylabel 的位置,以便您可以轻松地将两个图形的 ylabel 对齐在一起。

import matplotlib.pyplot as plt

plt.close('all')

#---- create figure ----

fwidth = 8.  # total width of the figure in inches
fheight = 4. # total height of the figure in inches

fig = plt.figure(figsize=(fwidth, fheight))

#---- define margins -> size in inches / figure dimension ----

left_margin  = 0.95 / fwidth
right_margin = 0.2 / fwidth
bottom_margin = 0.5 / fheight
top_margin = 0.25 / fheight

#---- create axes ----

# dimensions are calculated relative to the figure size

x = left_margin    # horiz. position of bottom-left corner
y = bottom_margin  # vert. position of bottom-left corner
w = 1 - (left_margin + right_margin) # width of axes
h = 1 - (bottom_margin + top_margin) # height of axes

ax = fig.add_axes([x, y, w, h])

#---- Define the Ylabel position ----

# Location are defined in dimension relative to the figure size  

xloc =  0.25 / fwidth 
yloc =  y + h / 2.  

ax.set_ylabel('yLabel', fontsize=16, verticalalignment='top',
              horizontalalignment='center')             
ax.yaxis.set_label_coords(xloc, yloc, transform = fig.transFigure)

plt.show(block=False)
fig.savefig('figure_margins.png')
Run Code Online (Sandbox Code Playgroud)

这将生成一个 8 英寸 x 4 英寸的图形,图形的左侧、右侧、底部和顶部的边距恰好为 0.95、0.2、0.5 和 0.25 英寸。这种方法的一个好处是边距的大小以绝对单位(英寸)定义,这意味着即使您更改图形的大小,它们也将保持一致。

对于 ylabel,水平方向上,标签顶部距离图的左边缘 0.25 英寸,而垂直方向上,标签的中心对应于轴的中心。请注意,由于 ylabel 旋转了 90 度,因此verticalalignment和 的含义horizontalalignment实际上是相反的。

下面显示了上述代码的输出,其中 y 轴限制分别设置为 [0, 1] 和 [0, 18]。

在此输入图像描述 在此输入图像描述