我想了解Matplotlib的“约束”布局引擎的装饰空间限制。在我的用例中,我必须在图的右侧添加大量装饰(例如不同的轴刻度和标签),并且我遇到了无法找到记录的限制。
下面的小测试显示
"x"
越来越向右移动。在 x_pos=1.3
周围的某个位置,约束开始将 "x"
移出可见区域。另一个观察结果是,稍微调整窗口大小可以解决此问题,即将 "x"
恢复到可见状态。
你对如何驯服野兽有什么建议吗?
from matplotlib import pyplot as plt
TEST_DECORATION = dict(s="x", horizontalalignment="center", verticalalignment="center")
def decorated_plot(x_pos: float):
"""Create (empty) plot w/ decoration at defined horizontal axes position."""
fig = plt.figure(layout="constrained")
ax = fig.add_subplot()
ax.text(x=x_pos, y=0.5, transform=ax.transAxes, **TEST_DECORATION)
ax.set_title(f"x = {x_pos}")
plt.show()
def main():
# explore the behavior for different values...
for x_pos in [1.1, 1.2, 1.25, 1.3, 1.32, 1.4]:
decorated_plot(x_pos)
if __name__ == "__main__":
main()
我认为问题来自于定义相对于轴大小的“x”位置。每次运行约束布局时,轴的大小都会发生变化,因此“x”相对于轴的位置也会发生变化。我不确定,但我认为约束布局着眼于艺术家当前在图中的位置,而不是直接知道“x”应该是轴尺寸的某个分数。如果适合您的用例,您可以通过将其与轴侧面保持固定距离来获得更可靠的结果。 annotate
比
text
提供更多控制位置的选项。例如,这里我将“x”从轴右侧放置为字体大小的一定倍数:from matplotlib import pyplot as plt
TEST_DECORATION = dict(horizontalalignment="center", verticalalignment="center")
def decorated_plot(x_pos: float):
"""
Create (empty) plot w/ decoration at defined distance in font sizes
from the right of the axes.
"""
fig = plt.figure(layout="constrained")
ax = fig.add_subplot()
ax.annotate("x", (1, 0.5), xycoords=ax.transAxes, xytext=(x_pos, 0),
textcoords='offset fontsize', **TEST_DECORATION)
ax.set_title(f"x = {x_pos}")
plt.show()
def main():
# explore the behavior for different values...
for x_pos in range(5, 41, 5):
decorated_plot(x_pos)
if __name__ == "__main__":
main()
输出示例: