Explain Codes LogoExplain Codes Logo

How to embed an image or picture in Jupyter Notebook, either from a local machine or from a web resource?

python
markdown
image-embedding
jupyter-notebook
Alex KataevbyAlex Kataev·Oct 31, 2024
TLDR

Embed images with IPython.display.Image in Jupyter Notebook:

Local file:

from IPython.display import Image Image('unicorn.png') # Replace 'unicorn.png' with your local image file.

Web image:

from IPython.display import Image Image(url='https://example.com/rainbow.png') # Replace the URL with the actual URL of the image.

Make your Markdown sparkle with images

Understanding the full capabilities of image embedding in Jupyter notebooks can drastically impact your data storytelling. Markdown cells come to the rescue:

Use the force of Markdown for image embedding

Markdown is your light saber for clean and effective image embedding. Use it for a local image:

![Alt text for the visually impaired](./path/to/unicorn.png) # Replace with your local image path.

For a web image:

![Alternative text](https://example.com/rainbow.png) # Replace with a direct web URL.

Remember to use filenames without spaces to prevent browser confusions, and prefer relative paths for better portability.

HTML tags: Your secret weapon for image adjustment

Sometimes you need to adjust the image size or alignment. HTML tags come to the rescue:

<img src="path/to/image.png" width="300" align="center"> # Adjust width or alignment to suit your narrative.

404 errors: The dark side and how to avoid it

Encountered a 404 error? Ensure Jupyter is running in the image-containing directory, or check your paths. If you notice %20 in your links, it's time to replace those HTML-encoded spaces with underscores or hyphens.

Insert Image: The fuss-free approach

For those who prefer GUI, Jupyter's "Insert Image" feature offers a smooth drag-and-drop experience.

Share the joy: Best practices for sharing notebooks

Be a good internet citizen: Store local copies

Remember to stash a local copy of all images for integrity and reproducibility. Especially useful when sharing notebooks with peers or on GitHub.

Hello JupyterLab: Adapting to the modern workflow

While JupyterLab limits some software interactions, you're still free to toss in images using markdown or HTML, adding life to your analysis.

Show off with dynamic visualizations

For added complexity, use code cells to load and interact with images:

from matplotlib import pyplot as plt import matplotlib.image as mpimg img = mpimg.imread('path/to/logo.png') # Loading the image; replace with your local image path. plt.imshow(img) # Displaying the image. plt.axis('off') # "These aren't the axes you're looking for." plt.show()