Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add space between sequential matplotlib figures?

How can I add space between multiple figures in the same Jupyter notebook cell in JupyterLab? For clarity, I am not trying to add space between subplots but rather between figures.

For example,

import matplotlib.pyplot as plt

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

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

will have both figures 'attached' and I want to add space between them similar to how print('\n') adds space between printed outputs.

To further clarify, using:

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

in JupyterLab leads to the new lines being placed in front of the plots, not between:

enter image description here

like image 552
thereandhere1 Avatar asked Mar 29 '26 01:03

thereandhere1


2 Answers

Simply add a blank figure to create the space between figures:

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

And control the spacing with f.set_figheight()

To produce this figure

like image 54
Daniel Dorman Avatar answered Apr 01 '26 09:04

Daniel Dorman


One approach would be to capture the plots in the 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])

Which results in:

plots separated by four empty lines

like image 22
krassowski Avatar answered Apr 01 '26 09:04

krassowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!