紧凑型布局长标题的马车?

2024-05-23 20:20:50 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

为什么每一个plt.tight_layout()在重新开始使用plt.clf()之后,这个数字还会缩小一点?在

获取以下片段:

plt.figure(1).clf()
plt.plot(range(10))
plt.title("Blah")
plt.tight_layout()

for _ in range(5):
    plt.figure(2).clf()
    plt.plot(range(10))
    plt.title("Blah")
    plt.tight_layout()

如预期,图1和图2是相同的。在

但现在把标题写得很长:

^{pr2}$

图3和图4不再相同,图4是水平收缩的,这种收缩随着循环次数的增加而增加。在

如果有人能解释一下。。。在

一些背景信息:

你可能会问“你到底为什么要把这些绘图的东西放到for循环中?”。实际上我没有,但我有一个交互式脚本,我可以重复同一个数字几次与一些变化,这个收缩似乎是一样的。。。在

我的python版本是:

Python 2.7.11 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:58:36) [MSC v.1500 64 bit (AMD64)]

顺便说一句,如果你把plt.tight_layout()调用的次数增加足够多,你最终会得到一个错误:

Traceback (most recent call last):

  File "<ipython-input-89-1a59da108bdf>", line 5, in <module>
    plt.tight_layout()

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\pyplot.py", line 1379, in tight_layout
    fig.tight_layout(pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1756, in tight_layout
    self.subplots_adjust(**kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 1612, in subplots_adjust
    self.subplotpars.update(*args, **kwargs)

  File "C:\Users\julien.bernu\AppData\Local\Continuum\Anaconda2\lib\site-packages\matplotlib\figure.py", line 226, in update
    raise ValueError('left cannot be >= right')

ValueError: left cannot be >= right

Tags: inlocallinepltusersappdatafilejulien
1条回答
网友
1楼 · 发布于 2024-05-23 20:20:50

在清除图形时,该图形保留其子lotparams,这些子参数已通过调用tight_layout进行了调整。在

考虑以下代码:

import matplotlib.pyplot as plt

left = []; right = []
def print_subplotparams(sp):
    t = "left={left:.3f}, right={right:.3f}, top={top:.3f}, bottom={bottom:.3f}"
    t = t.format(left=sp.left, right=sp.right, top=sp.top, bottom=sp.bottom)
    left.append(sp.left); right.append(sp.right)
    print(t)

fig = plt.figure(1)
print_subplotparams(fig.subplotpars)
fig.clear()

for _ in range(8):
    fig = plt.figure(1)
    # uncomment to see difference
    #fig.subplots_adjust(left=0.125, right=0.900, top=0.880, bottom=0.110)
    plt.plot(range(10))
    plt.title("Blahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh")
    plt.tight_layout()
    print_subplotparams(fig.subplotpars)
    fig.clear()

fig = plt.figure(2, figsize=(5,3))
plt.plot(range(len(left)), left, label="left")
plt.plot(range(len(right)), right, label="right")
plt.title("SubplotParams left/right as function of calls to tight_layout")
plt.xlabel("number of call to tight_layout")
plt.ylabel("left/right parameter")
plt.tight_layout()
plt.show()

产生:

enter image description here

可以看出,在每个循环步骤中,tight_layout会根据已经调整的参数进行调整,并使它们变得更小。在

为了防止在每个步骤中重置子批次参数

^{pr2}$

在这种情况下,tight_layout总是从相同的初始参数开始进行优化,并且它们的最终值不会更改。在

enter image description here

相关问题 更多 >