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?
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.
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.
This works for me:
<center><img src="picture.jpg"/></center>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With