Introduction
Modern research combines computation with documentation. Integrating LaTeX with Python, R, and Jupyter creates powerful reproducible research workflows.
This guide covers connecting LaTeX with computational tools.
Python Integration
Pylatex Library
from pylatex import Document, Section, Itemize
doc = Document()
doc.preamble.append(Command('title', 'My Document'))
doc.preamble.append(Command('date', 'today'))
with doc.create(Section('Introduction')):
doc.append('This is an introduction.')
with doc.create(Itemize()) as itemize:
itemize.add_item('First item')
itemize.add_item('Second item')
doc.generate_pdf('my_document')
Jinja2 Templates
from jinja2 import Template
template = Template(r'''
\documentclass{article}
\title{ {{ title }} }
\author{ {{ author }} }
\begin{document}
\maketitle
{{ content }}
\end{document}
''')
output = template.render(
title='Generated Report',
author='Author Name',
content='Report content here...'
)
with open('output.tex', 'w') as f:
f.write(output)
R Integration
Knitr
Use R Markdown for integrated documents:
---
title: "Analysis Report"
author: "Author"
output: pdf_document
---
Then in R:
library(knitR)
render("document.Rmd")
Sweave
Sweave integrates R and LaTeX:
\documentclass{article}
\begin{document}
Results:
<<>>=
summary(cars)
@
\end{document}
Compile with:
R CMD Sweave document.Rnw
pdflatex document.tex
Jupyter Integration
nbconvert
# Convert notebook to LaTeX
jupyter nbconvert --to latex notebook.ipynb
# With template
jupyter nbconvert --to latex --template article notebook.ipynb
jupytext
# Convert to LaTeX
jupytext --to latex notebook.ipynb
# Convert from LaTeX to notebook
jupytext --to ipynb document.tex
Automation Scripts
Python Build Script
#!/usr/bin/env python3
"""Build LaTeX document with Python integration."""
import subprocess
import sys
from pathlib import Path
def run_command(cmd):
result = subprocess.run(cmd, shell=True)
return result.returncode
def build_document(tex_file):
name = Path(tex_file).stem
# Run pdflatex
run_command(f'pdflatex -interaction=nonstopmode {tex_file}')
# Run biber if needed
run_command(f'biber {name}')
# Final pdflatex
run_command(f'pdflatex -interaction=nonstopmode {tex_file}')
print(f'Built {name}.pdf')
if __name__ == '__main__':
build_document(sys.argv[1])
Makefile
TEX = pdflatex
PDFLATEX = pdflatex -interaction=nonstopmode
BIBER = biber
%.pdf: %.tex
$(PDFLATEX) $<
$(BIBER) $(<:.tex=)
$(PDFLATEX) $<
$(PDFLATEX) $<
.PHONY: clean
clean:
rm -f *.aux *.bbl *.blg *.log *.out *.toc
Data Processing
Generate Tables from Data
import pandas as pd
import numpy as np
# Create sample data
df = pd.DataFrame({
'A': [1, 2, 3],
'B': [4, 5, 6]
})
# Generate LaTeX table
latex_table = df.to_latex(index=False)
print(latex_table)
Generate Plots
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({'x': [1, 2, 3], 'y': [4, 5, 6]})
plt.figure()
plt.plot(df['x'], df['y'])
plt.savefig('plot.pdf')
Then include in LaTeX:
\usepackage{graphicx}
\begin{figure}
\centering
\includegraphics{plot}
\caption{Generated Plot}
\end{figure}
Best Practices
Workflow Tips
- Use version control
- Separate data from code
- Document everything
- Automate builds
- Test reproducibility
Conclusion
Integrating LaTeX with Python, R, and Jupyter enables powerful reproducible research workflows. Use these tools to automate document generation from computational analysis.
Comments