Home > front end >  How can I display image data in Jupyter notebook AND control its position?
How can I display image data in Jupyter notebook AND control its position?

Time:02-20

I don't understand why I cannot find any examples on this, maybe its not possible; I've seen 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?

CodePudding user response:

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

CodePudding user response:

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.

  • Related