Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display image jupyter notebook aligned centre

I am using the following code to insert an image in Jupyter notebook which is compatible with html conversion:

from IPython.display import Image

Image(filename="picture.jpg")

This works nicely except the fact that it is left aligned and I need it centre/middle aligned. Is there any method that I can set it to be aligned correctly?

like image 698
pouya Avatar asked Sep 27 '17 05:09

pouya


People also ask

How do you center a plot in Jupyter Notebook?

The Plots in the Jupyter Notebook can be Centered by Using HTML CSS Code Snippet. The Code for aligning the plots at center is shown below, by using this Code Snippet all the plots can be centered in the Jupyter Notebook. Make Sure you run this Code Snippet in Code Cell, not in Markdown Cell.

Which method is used to display image in the Jupyter?

To display the image, the Ipython. display() method necessitates the use of a function. In the notebook, you can also specify the width and height of the image.


2 Answers

This works for me:

<center><img src="picture.jpg"/></center>
like image 54
Steve Roberts Avatar answered Sep 28 '22 23:09

Steve Roberts


Many browsers (Chrome, Firefox) are only supporting HTML 5, so this syntax no longer works, even within the notebook itself.

<img src="picture.jpg" align="center"/>

because align="center" has been deprecated. Now you should use CSS style properties and the various margin definitions.

<img src="picture.jpg" style="margin-left:auto; margin-right:auto"/>

or

<img src="picture.jpg" style="margin:auto"/>

See here for more discussion around this. This makes it look properly centered while being displayed in your Notebook. But frustratingly doesn't work (still left justified) when you export your notebook to HTML. Inspecting the HTML that is generated you find that the <img> is embedded in a <p> element and this throws the whole thing off. So you have to add an additional display=block property, making the whole thing

<img src="picture.jpg" style="display=block; margin:auto"/>

This will center the image in your notebook, exported HTML, and exported Markdown files. Thanks to these guys for the tip on the display=block bit.

To get a centered bit of text underneath the image (like a figure title) I throw in a

<p style="text-align: center">
    <b>Figure N. My Cool Figure</b>
</p>

afterwards. The whole setup is then

<img src="picture.jpg" style="display=block; margin:auto"/>
<p style="text-align: center">
    <b>Figure N. My Cool Figure</b>
</p>
like image 32
Tom Johnson Avatar answered Sep 29 '22 00:09

Tom Johnson