Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert figure into iPython markdown cell

In iPython I create an image in one cell using the Pandas plot function. In a different markdown cell in the same notebook I would like to add this figure inline.

Is it possible to reference notebook internal figures in a markdown cell without saving them to disk?

like image 932
Paul Dixon Avatar asked Oct 16 '25 14:10

Paul Dixon


2 Answers

Edit : it's in the same notebook !

Yes you can, but not in the markdown cell (as far as I know).

Just save your figure in a figure object (if not already done by fig = plt.figure() )

plt.plot(...)
fig = plt.gcf()

And then call fig wherever in the notebook. To get rid of the input cell after html conversion, see below.


If between 2 distinct notebooks (but also work in the same notebook)

The closest I can get to your request is to use the base64 address of the image :

So far it seems that markdown doesn't deal well with this, but you can put the following in a %%html magic cell.

%%html
<img alt="Image" src="data:image/png;base64,iVBORw0KG ... hEJRU5ErkJggg==" />

With

data:image/png;base64,iVBORw0KG ... hEJRU5ErkJggg==

being your image in base64. You can get this address just by right clicking on the image in the other notebook and select "copy image address" (if it's inline image). Otherwise you can use image to base64 converter.

Here you'll still get the input cell visible, but if you eventually convert your notebook in html, you'll be able to hide the input cells with some Javascript. (See here for how to, disclaimer: it's my answer (to my question)).

At the end, you'll be able to hide the %%htmlmagic cell while keeping the image.

Hope this helps

like image 95
jrjc Avatar answered Oct 19 '25 05:10

jrjc


You can do it easily if you keep the Axes instance when creating the figure:

t = arange(0,6,0.01)
x = sin(t)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(t,x)

If you're using pandas plotting functions, first create the axes as before and then pass the instance to the pandas plotting function as argument: pandas.DataFrame.plot(ax=ax). An example:

from pandas import Series, date_range
ts = Series(randn(1000), index=date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

fig = plt.figure()
ax = fig.add_subplot(111)
ts.plot(ax=ax)

Then you can reuse the same figure in another cell:

display(ax.get_figure())
like image 28
lmillefiori Avatar answered Oct 19 '25 03:10

lmillefiori