gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:42:15 25 4
gpt4 key购买 nike

我用 Python 2.7 在 Matplotlib 中制作了 2 个图。这些图被保存到 *.png 文件中。保存后,两张图片的分辨率相同 - 宽度 = 1099 像素,高度 = 619 像素。

但是,当我垂直对齐保存的 *.png 图像时(附在下面),y 轴和图像最左边的点之间的间距不相同 - 请参见 a和下图中的 benter image description here

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

点击图片放大查看。

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

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

注 2:我创建我的情节使用:

fig = plt.figure(1)
ax = fig.add_subplot(111)
fig.tight_layout()

最佳答案

如果我想在 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')

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

对于 ylabel,在水平方向上,标签的顶部位于距离图形左边缘 0.25 英寸的位置,而在垂直方向上,标签的中心对应于轴的中心。请注意,由于 ylabel 上的 90 度旋转,verticalalignmenthorizo​​ntalalignment 的含义实际上是相反的。

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

enter image description here enter image description here

关于python - Matplotlib:图形左边缘和 y 轴之间的固定间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31928209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com