0

I don't understand why I cannot find any examples on this, maybe its not possible; I've seen How to show PIL Image in ipython notebook and How to convert a NumPy array to PIL image applying matplotlib colormap and cannot figure this out.

Say I have this Jupyter code:

import io

import matplotlib.figure
import matplotlib.pyplot as plt

%matplotlib inline
fig = matplotlib.figure.Figure(facecolor=(1.0,1.0,1.0,1.0))
fig.text(0, 0, "Hello World", fontsize=20)
with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png", bbox_inches="tight",
                pad_inches=0)
    buf.seek(0)
    rgba = plt.imread(buf)


from IPython.display import display
from IPython.display import Markdown as md, Javascript, HTML

display(md("I want this text **above** the image"))

plt.imshow(rgba)

display(md("I want this text **below** the image"))

This is what I get:

enter image description here

... but this is what I want instead:

enter image description here

... or in case I'm not clear enough, this is the end result I desire:

enter image description here

How can I achieve that?

sdbbs
  • 4,270
  • 5
  • 32
  • 87
  • In addition to the example I posted that changes least amount in your code, you could have saved the plot of the array as an image to a file and used `from IPython.display import Image` combined with `display(Image())` to display the result sandwiched between your two markdown text lines. – Wayne Feb 19 '22 at 19:11

2 Answers2

1

An option is to control the output plot differently so that you don't let Jupyter separate it out from the display commands:

import io

import matplotlib.figure
import matplotlib.pyplot as plt

fig = matplotlib.figure.Figure(facecolor=(1.0,1.0,1.0,1.0))
fig.text(0, 0, "Hello World", fontsize=20)
with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png", bbox_inches="tight",
                pad_inches=0)
    buf.seek(0)
    rgba = plt.imread(buf)


from IPython.display import display
from IPython.display import Markdown as md
im = plt.imshow(rgba)
plt.close() # from https://www.kite.com/python/answers/how-to-hide-a-figure-from-being-shown-in-matplotlib-in-python

display(md("I want this text **above** the image"))

display(im.figure)

display(md("I want this text **below** the image"))

Explanation:
It uses plt.close() to hide what normally jupyter would display as the result of plt.imshow(rgba) separate from the output of the display functions in the code.
Then we can use the handle it was assigned to, im, to call the figure attribute of im inside a display function sandwiched between the other two display commands.

Demonstration option:
That code will work when pasted in new notebooks opened from inside Jupyter sessions launched from here, served via MyBinder.org.

Wayne
  • 6,607
  • 8
  • 36
  • 93
0

Just add plt.show() when you want to display the plot. So here after the instruction plt.imshow(rgba)

rehaqds
  • 414
  • 2
  • 6