我想在等宽的轴上绘制一组多边形,并在图形上应用紧密布局.

然而,当同时使用等宽和紧凑布局时,图形大小似乎没有得到正确调整.

try 1

等宽紧凑布局

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1)
l = 5
h = 1
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)
fig.tight_layout(pad=0.25)
plt.show()

输出:注意顶部和底部的额外空间.还要注意,y轴标签超出界限.

enter image description here

try 2

布局紧凑,无等宽

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1)
l = 5
h = 1
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
# ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)
fig.tight_layout(pad=0.25)
plt.show()

输出:效果良好,但纵横比不相等

enter image description here

如何实现紧密布局and等纵横比?

推荐答案

如果图形的纵横比(默认大小从rcParams["figure.figsize"]默认为[6.4, 4.8],即纵横比为1.33)与轴的纵横比不同,则会出现额外的边距.为了避免这种情况,需要调整地物的纵横比,以匹配轴的纵横比,包括记号和标签.您可以使用get_tightbbox after绘制图形(例如使用draw_without_rendering).

为了获得更好的视觉效果,我建议使用constrained而不是tight布局.

import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

fig, ax = plt.subplots(1,1, layout='constrained')
l = 5
h = 1
fig.set_size_inches(10,2)
poly = Polygon(
    np.array([
        [0,0],
        [l,0],
        [l,h],
        [0,h]
    ]),
    edgecolor="black",
    facecolor="gray",
)
ax.add_patch(poly)
ax.set_aspect("equal")
ax.set_xlim(0,l)
ax.set_ylim(0,h)
ax.set_xlabel(r"$x$")
ax.set_ylabel(r"$y$", rotation=0, labelpad=5)

# adjust Figure aspect ratio to match Axes
fig.draw_without_rendering()
tb = fig.get_tightbbox(fig.canvas.get_renderer())
fig.set_size_inches(tb.width, tb.height)

plt.show()

enter image description here

Python-3.x相关问答推荐

在Python中从mySQL获取多行

While循环不停止地等待,直到时间.睡眠结束

Strawberry FastAPI:如何调用正确的函数?

可以在 Python 的上下文管理器中调用 sys.exit() 吗?

在 python 中使用正则表达式在行尾查找特定元素

如何沿单列获取嵌套列表中的唯一值?

txt 文件与不同的分隔符到整数列表

获取字符串中的两个工作日之间的差异

如何将虚拟变量列转换为多列?

将字典列表展平为数据框列

聚合(aggregate)为最多包含两个元素的列表

python 3:如何判断一个对象是否是一个函数?

在初始化之前禁用`__setattr__`的干净方法

两个Pandas数据框中的共同列列表

Python:如何判断一个项目是否被添加到一个集合中,没有 2x(hash,lookup)

Python图例属性错误

为现有项目创建virtualenv

TypeError:只有整数标量数组可以转换为标量索引

带有自定义标头的 urllib.urlretrieve

哪个更有效:Python 文档字符串还是类型提示?