Jagerber48
Jagerber48

Reputation: 925

How to optionally show figure in Jupyter notebook

I would like to have code which optionally displays a figure which has been generated using matplotlib in a Jupyter notebook. The reason I want this is that the figures are saved to the drive and sometimes it would be nice to not have to show them in the notebook itself.

Furthermore, I would like it to possible for multiple plots to be created within a single cell with some shown and some not shown.

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(-5, 5, 100)
y1 = t
y2 = t**2
show_fig1 = True
show_fig2 = True

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot(t,y1)
fig1.savefig('fig1.png')
print('Showing Figure 1:')
if show_fig1:
    plt.show()

fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
ax2.plot(t,y2)
fig2.savefig('fig2.png')
print('Showing Figure 2:')
if show_fig2:
    plt.show()

print('Done Showing Figures')

The above code does not work but is my best effort.

If show_fig1=False and show_fig2=True then fig1 ends up being displayed as soon as plt.show() is called in the fig2 block of code.

If show_fig1=True and show_fig2=False then fig1 shows up correctly but fig2 still appears at the end of the cell (after 'Done Showing Figures' is printed).

If they are both false then both plots appear at the very end of the cell.

I have tried other combinations like using fig1.show() instead of plt.show() but this doesn't seem to work. I've tried various adjustments like using or not using %matplotlib inline or ion() and ioff().

Any suggestions?

Upvotes: 0

Views: 283

Answers (1)

Matt Hall
Matt Hall

Reputation: 8122

Maybe this works for you:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(-5, 5, 100)
y1 = t
y2 = t**2
show_fig1 = True
show_fig2 = True

fig, ax = plt.subplots()
ax.plot(t, y1)
plt.savefig('fig1.png')
if show_fig1:
    plt.show()
else:
    plt.close()

fig, ax = plt.subplots()
ax.plot(t, y2)
plt.savefig('fig2.png')
if show_fig2:
    plt.show()
else:
    plt.close()

print('Done Showing Figures')

Upvotes: 2

Related Questions