How can I center the position of a matplotlib figure after nbconvert?

2.3k views Asked by At

I would like to convert my jupyter notebook to a presentation using nbconvert. Is it possible to position a matplotlib figure at the center of a slide?

In jupyter, I prevent my code from displaying, and then make a plot.

(RawNBConvert)

<style type="text/css">
.input_prompt, .input_area, .output_prompt {
    display:none !important;
}
</style>

(python)

%matplotlib inline
import matplotlib.pyplot as plt

plt.plot([1,2,3]);

Then, this notebook is converted to an html using the following command:

jupyter nbconvert mynote.ipynb --to slides

The resulting html renders like this. enter image description here

I have been trying to center this plot in my slide. I looked at my reveal.css file, but could not figure out which part to change. Does anyone know how I can fix this?

I use jupyter 1.0.0 and nbconvert 4.2.0.

2

There are 2 answers

0
Taro Kiritani On BEST ANSWER

There might be better solutions, but adding a few lines in the RawNBConvert cell fixed this problem. I hope this causes no side effect.

<style type="text/css">
.input_prompt, .input_area, .output_prompt {
    display:none !important;
}

div.output_png {
  display: flex;
  justify-content: center;
}

</style>

enter image description here

0
bmarcov On

just to add details to the solution by Taro:

A "RawNBConvert" cell can be created by

  1. going to View -> Cell Toolbar -> Raw Cell Format
  2. creating a new cell of type (Cell -> Cell Type) "Raw NBConvert"
  3. setting the "Raw NBConvert Format" to HTML

The style code of this solution can be added to the newly-created cell. NBConvert should pick it up automatically.

Notice that the solution posted disables the display of the input area (i.e., the script used to generate the image, as well as any script in the slides). This is similar to setting the -no-input option when converting the notebook to slides.

Last, what actually worked for me was using this (you might want to adjust some parameters):

<style type="text/css">
.input_prompt, .input_area, .output_prompt {
    display:none !important;
}

div.output_png {
    max-width: 100%;
    width: 100%;
}

div.output_png img {
   width: 80%;
   margin-left: auto;
   margin-right: auto;
   display: block;
}

</style>

Hope this helps