问题
I am using Jupyter Notebook nbconvert (Save as menu) to export as pdf via Latex. However, the pdf file is not in a good shape. For example, some wide tables are shown well. I would prefer to have a box for tables to be resized to the width of the page. Is there any style, template that I can use to have nice reports and how I may ask nbconverter to use that style?
Here is the Latex output:
I would like something like this:
回答1:
Looks like Pandas gained a ._repr_latex_()
method in version 0.23. You'll need to set pd.options.display.latex.repr=True
to activate it.
Without latex repr:
With latex repr:
Check out the options to get the formatting close to what you want. In order to match your desired output exactly, you'll need to use a custom latex template.
Edited to provide more information on templates:
Start here for general information about templates. You can create a .tplx
file in the same path as your notebook and specify it as the template when running nbconvert
from the command line: !jupyter nbconvert --to python 'example.ipynb' --stdout --template=my_custom_template.tplx
. Alternatively, you can specify a default template to use when exporting as Latex via the menu by modifying the jupyter_notebook_config.py
file in your ~.jupyter
directory. If this file doesn't exist already, you can generate it by running the command jupyter notebook --generate-config
from the command line. I have my template sitting in the ~/.jupyter
directory as well, so I added the following to my jupyter_notebook_config.py
:
# Insert this at the top of the file to allow you to reference
# a template in the ~.jupyter directory
import os.path
import sys
sys.path.insert(0, os.path.expanduser("~") + '/.jupyter')
# Insert this at the bottom of the file:
c.LatexExporter.template_file = 'my_template' # no .tplx extension here
c.LatexExporter.template_path = ['.', os.path.expanduser("~") + '/.jupyter'] # nbconvert will look in ~/.jupyter
To understand a bit about how the templates work, start by taking a look at null.tplx. The line ((*- for cell in nb.cells -*))
loops over all the cells in the notebook. The if
statements that follow check the type of each cell and call the appropriate block.
The other templates extend null.tplx
. Each template defines (or redefines) some of the blocks. The hierarchy is null->display_priority->document_contents->base->style_*->article
.
Your custom template should probably extend article.tplx
and add some Latex commands to the header that sets up the tables the way you want. Take a look at this blog post for an example of setting up a custom template.
回答2:
Any setting that change the table size to fit it in the width of the page?
Latex code is something like this: \resizebox*{\textwidth}{!}{%
来源:https://stackoverflow.com/questions/52501459/jupyter-nbconvert-latex-export-theme