我不希望将整个笔记本导出为pdf -我已经搜索并找到了该问题的解决方案。我只想将我笔记本中的绘图导出为pdf。有没有一个Python库可以做到这一点?
发布于 2020-04-10 12:50:25
Jupyter nbconvert命令允许指定自定义模板。
Michael Goerz已经在这里为LaTeX/PDF编写了一个完整的自定义模板:https://gist.github.com/goerz/d5019bedacf5956bcf03ca8683dc5217
要只打印图形,您可以将其修改为清除除输出单元格以外的任何部分,如下所示:
% Tell the templating engine what output template we want to use.
((* extends 'article.tplx' *))
% Template will setup imports, etc. as normal unless we override these sections.
% Leave title blank
((* block title -*))
((*- endblock title *))
% Leave author blank
((* block author -*))
((* endblock author *))
% Etc.
((* block maketitle *))
((* endblock maketitle *))
% Don't show "input" prompt
((*- block in_prompt -*))
((*- endblock in_prompt -*))
% Hide input cells
((*- block input -*))
((*- endblock input -*))
% Don't show "output" prompt
((*- block output_prompt -*))
((*- endblock output_prompt -*))
% Let template render output cells as usual要生成LaTeX文件,请将上面的代码另存为custom_article.tplx并运行:
jupyter nbconvert --to=latex --template=custom_article.tplx file.ipynb
要在单个命令中生成LaTeX文件和PDF,请执行以下操作:
jupyter nbconvert --to=pdf --template=custom_article.tplx file.ipynb
发布于 2020-04-10 09:11:04
这可能不是最优雅的答案,但它也非常灵活,以防您希望做更多的事情,而不仅仅是将每个绘图放在一页上。在将所有图形导出为图像后,可以使用LaTeX将所有图形收集到单个pdf中。下面是一个示例,我们将图形保存为report/imgs/*.png,然后编写一个report/report.tex文件,并使用pdflatex将其编译为最终的report/report.pdf。
import numpy as np
import matplotlib.pyplot as plt创建并保存两个镜像:
plt.bar(np.arange(5), np.arange(5)*2)
plt.savefig('report/imgs/fig1.png')plt.bar(np.arange(6), np.arange(6)**2 - 1, color = 'g')
plt.savefig('report/imgs/fig2.png')编写一个.tex文件以显示这两个图像:
img_data = ['fig1', 'fig2']
latex_src = '\\documentclass{article}\n'
latex_src += '\\usepackage{graphicx}\n'
latex_src += '\\graphicspath{{./imgs/}}\n'
latex_src += '\\begin{document}\n'
for image in img_data:
latex_src += '\t\\begin{figure}[h]\n'
latex_src += f'\t\t\\includegraphics{{{image}}}\n'
latex_src += '\t\\end{figure}\n'
latex_src += '\\end{document}'
with open('report/report.tex', 'w', encoding = 'utf-8') as handle:
handle.write(latex_src)
print(latex_src)\documentclass{article}
\usepackage{graphicx}
\graphicspath{{./imgs/}}
\begin{document}
\begin{figure}[h]
\includegraphics{fig1}
\end{figure}
\begin{figure}[h]
\includegraphics{fig2}
\end{figure}
\end{document}最后编译:
!cd report && pdflatex report.texhttps://stackoverflow.com/questions/61132129
复制相似问题