【问题标题】:How to add space between sequential matplotlib figures?如何在顺序 matplotlib 图形之间添加空格?
【发布时间】:2023-03-13 21:24:02
【问题描述】:

如何在 JupyterLab 的同一个 Jupyter 笔记本单元格中的多个图形之间添加空格? 为清楚起见,我不是要在子图之间添加空间,而是在图形之间添加空间。

例如,

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 中导致新线被放置在图的前面,而不是在它们之间:

【问题讨论】:

  • 只需print('\n') 应该再次成功。
  • @ddg,我已经试过了。它没有。
  • 尝试添加plt.tight_layout()matplotlib.org/3.3.3/tutorials/intermediate/…
  • @rzaratx,这将有助于子图。我的目标是在单个数字之间添加空间
  • 嗯,它在我的 Jupyter 中工作

标签: python python-3.x matplotlib jupyter-lab


【解决方案1】:

一种方法是捕获 ipywidgets 输出中的图:

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])

结果:

【讨论】:

  • 我一直在寻找一种利用 matplotlib 功能的更简单、更优雅的方法。
  • 我自己会很好奇。试图帮助我掌握的知识。 matplotlib 的有状态 API 很奇怪,会导致类似的问题,因此我总是避免它更喜欢其他库。
【解决方案2】:

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

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()控制间距

To produce this figure

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多