我想在等宽的轴上绘制一组多边形,并在图形上应用紧密布局。
但是,当同时使用等长宽比和紧凑布局时,图形大小似乎没有得到正确调整。
尝试 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 轴标签超出范围。
尝试 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()
输出:效果很好,除了纵横比不相等
如何实现紧凑的布局和等长宽比?
最佳答案
如果图形的纵横比(rcParams["figure.figsize"]
的默认大小默认为 [6.4, 4.8]
,即纵横比,则会出现额外的边距比率为 1.33) 与轴的纵横比不同。为避免这种情况,您需要调整图形的纵横比以匹配轴的纵横比,包括刻度和标签。您可以使用 get_tightbbox
获取它在您绘制图形后(例如使用 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()
关于python-3.x - matplotlib.pyplot 具有等宽和紧凑布局的多边形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73046988/