Google Colab Insert a Saved Figure in a Text box

Viewed 359

I am writing a Colab notebook to share with my students, so I want a copy of the notebook to run in other Google accounts.

I do am plotting some data in a python/jupyter notebook in Colab and saving it. Like

plt.savefig("Jump1-04.png")

In a cell later I want to use this image, so I tried various Markdown and or HTML approaches to include this image. Examples:

!()["Jump1-04.png"]

Or

<img src="/content/Jump1-02.png" />

None worked. My puzzle is that my code can open this file using open("Jump1-04.png", 'r'), so the notebook code knows where files are saved, but Text cells don't. !pwd returns /content and !ls /content returns Jump1-04.png. That is why I tried putting /content in the HTML code above.

I want to avoid the pain ITB of finding the file using Google Drive, publically sharing the link, then using that link in the Text cell.

Why can't the Text cells simply find the files I save from the code cells?

1 Answers

I'm not 100% sure what was "incorrect" about your lines of code either, but I had to play around with the plt.show() and plt.imshow(), and I also defined the figure to be saved initially (i.e. "fig") so "fig.savefig()" instead of "plt.savefig()", which isn't much of a difference but this works according to your description:

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
fig = plt.figure(figsize = (10, 5), num = 1, clear = True)
ax = plt.subplot(1, 1, 1, xticks = [], yticks = [], frameon = False)
ax.plot(np.arange(0, 10, 1), color = [0, 0.5, 1], lw = 5)
plt.show()
fileName = 'Jump1-04.png'
fig.savefig(fileName)

To open the saved file (in a later, separate cell):

import PIL
from PIL import Image
fig = plt.figure(figsize = (10, 5), num = 1, clear = True)
ax = plt.subplot(1, 1, 1, xticks = [], yticks = [], frameon = False)
fileName = 'Jump1-04.png'
thisImage = Image.open(fileName)
thisImage = ax.imshow(thisImage)
plt.show(thisImage)

To address the first sentence which sounds like you want these plots or images on the internet with a url link that is public and which you and your students can access, I haven't found a solution yet; I'll update if/when I do.

Related