Alex Shroyer
Alex Shroyer

Reputation: 3829

How to capture a cell's output for use in another cell?

In org-mode, I can name the output of a code block and include it elsewhere in the document.
Is it possible to do this (or something similar) in a colab .ipynb file, or within a Jupyter notebook in general?

For example, I can make a cell with some Python code that generates a plot:

import matplotlib.pyplot as plt
plt.plot([0,2,1,4,9])

After executing, the plot appears below the code cell. So far so good.
But how do I capture this plot and to use it elsewhere in the notebook?

My hope is there is some syntax so that I can include the plot in a markdown cell, for example:

# this is my title
As you can see, the numbers go up and down in the plot:

![][some_magic_link_here]

Here is some more text to explain the plot.

Does such a feature exist in colab?

Upvotes: 0

Views: 522

Answers (1)

Bob Smith
Bob Smith

Reputation: 38619

Good news - embedding an image in another markdown cell is self-service. Here's an example:

enter image description here

Full notebook: https://colab.research.google.com/drive/1PF-hT-m8eZN2CBzFkMp9Bvzj9pSBQVYn

The key bits are:

  1. Using IPython.display.Markdown is order to programmatically construct the markdown.
  2. In addition to rendering, save the matplotlib figure using savefig.
  3. Include the image data in the markdown after base64 encoding.

Upvotes: 1

Related Questions