10

When generating a pdf in jupyter notebook, everything works great, but I would like to keep the inline figures inside the pdf, as well as the notebook.

Here is my code:

%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')

save_figures = True

x = np.arange(0, 20, 0.1)
y = np.sin(x)
plt.figure()
plt.plot(x, y)
if save_figures:
    plt.savefig('test.png')
plt.show()

The figures appear inline, but in the pdf what is printed instead is:

<IPython.core.display.Javascript object>

<IPython.core.display.HTML object>

The same thing appears in the pdf if I export from the web or use nbconvert to export to pdf from the command line.

Are there any additional commands that I need to invoke in order to get this to work?

Thomas K
  • 39,200
  • 7
  • 84
  • 86
areth
  • 113
  • 1
  • 2
  • 6
  • 1
    I came across the same issue. I want to use it for 3d plot to adjust the view angles etc, so `%matplotlib inline` is not an option for me. Is there going to be a fix for that issue? – DaPhil Jul 26 '16 at 08:12
  • Reported as a bug: https://github.com/jupyter/notebook/issues/3295 – Jay M Feb 02 '18 at 16:43

2 Answers2

14

If you change the %matplotlib notebook to %matplotlib inline, then PDF export with jupyter's nbconvert works fine for me. The %matplotlib notebook magic renders the plot in an interactive way that I suspect isn't properly recognized by LaTeX, which is used during the PDF conversion.

Alternatively, if you have to use %matplotlib notebook for some reason, the export to HTML with jupyter's nbconvert (jupyter nbconvert --to='html' Test.ipynb) seems to preserve the plot. I am then able to print this HTML file to a PDF from a web browser and the plot is present in the final PDF.

Michelle Lynn Gill
  • 1,104
  • 10
  • 10
  • Perfect! Yep, interactive plots don't seem to be rendered but using `inline` works fine. Thank you! – areth Feb 10 '16 at 23:19
  • 1
    Do you know if there's a way to override `%matplotlib notebook` from the command line so static figures are being exported instead? – Tom Jul 25 '17 at 12:17
  • `%matplotlib inline` did it for me. – wander95 Jan 17 '19 at 15:41
4

Crude solution to interactive problem: in interactive function save figure to a file

fig.savefig("pieCharts.png")

in next cell display a file:

from IPython.display import Image
Image("pieCharts.png")

In PDF only output of the 2nd line will be displayed with image as changed in interactive function.

  • This worked for me for PDF export, and also solved issues with the notebook file size and image caching. – phhu Jun 03 '21 at 10:39