如何在连续的Matplotlib图形之间添加间距?

3
我可以帮您翻译如下内容:

在JupyterLab中的同一笔记本单元格中,如何在多个图形之间添加空格?需要说明的是,我不是要在子图之间添加空格,而是在图形之间添加空格。

例如,

import matplotlib.pyplot as plt

fig1 = plt.figure()
_ = plt.plot(x,y)

fig2 = plt.figure()
_ = plt.hist(z)

我将会有两个“附加”的数字,我希望在它们之间添加空格,就像 print('\n') 在输出之间添加空格一样。

为了进一步澄清,使用:

import matplotlib.pyplot as plt

fig1 = plt.figure()
_ = plt.plot([1, 2], [2, 3])

print('\n' * 4)

fig2 = plt.figure()
_ = plt.hist([1, 2, 3])

在JupyterLab中,回车键会使新行出现在图表前面而不是之间:

enter image description here


@ddg,我已经试过了。不行。 - thereandhere1
尝试添加plt.tight_layout()。https://matplotlib.org/3.3.3/tutorials/intermediate/tight_layout_guide.html#sphx-glr-tutorials-intermediate-tight-layout-guide-py - rzaratx
1
哇,它在我的Jupyter中运行成功了。 - ddg
它在JupyterLab中无法工作。虽然已经进行了适当的标记,但标题和正文中没有提到,这可能是混淆的源头。 - krassowski
我的错误。你是对的。 - Mad Physicist
显示剩余3条评论
2个回答

4

只需添加一个空白的图形即可创建图形之间的间隔:

import matplotlib.pyplot as plt

fig1 = plt.figure()
_ = plt.plot([1, 2], [2, 3])

f,ax = plt.subplots()
f.set_visible(False)
f.set_figheight(2) # figure height in inches

fig2 = plt.figure()
_ = plt.hist([1, 2, 3])

使用 f.set_figheight() 控制间距

生成此图


3

一种方法是在ipywidgets的Output中捕获图表:

import matplotlib.pyplot as plt
import ipywidgets as widgets

out1 = widgets.Output()
out2 = widgets.Output()
spacer = widgets.Output()

with out1:
    fig1 = plt.figure()
    _ = plt.plot([1, 2], [2, 3])
    plt.show()

with out2:
    fig2 = plt.figure()
    _ = plt.hist([1, 2, 3])
    plt.show()

with spacer:
    print('\n' * 4)

widgets.VBox([out1, spacer, out2])

这将导致:

plots separated by four empty lines


我正在寻找一种更简单、更优雅的方法,利用matplotlib的功能。 - thereandhere1
1
我自己也会感到好奇。尽力用我所掌握的知识来帮助。Matplotlib的有状态API很奇怪,会导致类似这样的问题,因此我总是避免使用它,更喜欢其他的库。 - krassowski

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接