| 1 |
%% Copyright 2021-2026 Tobias Enderle |
| 2 |
%% |
| 3 |
%% This work may be distributed and/or modified under the |
| 4 |
%% conditions of the LaTeX Project Public License, either version 1.3c |
| 5 |
%% of this license or (at your option) any later version. |
| 6 |
%% The latest version of this license is in |
| 7 |
%% http://www.latex-project.org/lppl.txt |
| 8 |
%% and version 1.3c or later is part of all distributions of LaTeX |
| 9 |
%% version 2005/12/01 or later. |
| 10 |
|
| 11 |
% DESCRIPTION |
| 12 |
% Demonstrates how *matplotlib* plots can be generated and included in a |
| 13 |
% document using *PGF* |
| 14 |
|
| 15 |
\documentclass{article} |
| 16 |
|
| 17 |
\usepackage{pyluatex} |
| 18 |
\usepackage{unicode-math} |
| 19 |
\usepackage{pgf} |
| 20 |
\usepackage{url} |
| 21 |
|
| 22 |
\begin{document} |
| 23 |
|
| 24 |
In this document, we demonstrate how \emph{matplotlib} plots can be generated |
| 25 |
and included in a document. In the Python code in this document, the plot is |
| 26 |
configured and saved to PGF\footnote{\url{https://ctan.org/pkg/pgf}} code. |
| 27 |
The PGF code is then included in the document and creates the plot. |
| 28 |
|
| 29 |
To avoid intermediate files, the PGF code is saved into an in-memory file |
| 30 |
using the Python \verb|io.StringIO| class% |
| 31 |
\footnote{\url{https://docs.python.org/3/library/io.html#io.StringIO}}. |
| 32 |
|
| 33 |
\begin{center} |
| 34 |
\begin{python} |
| 35 |
# example based on |
| 36 |
# https://matplotlib.org/stable/gallery/lines_bars_and_markers/simple_plot.html |
| 37 |
import matplotlib.pyplot as plt |
| 38 |
import numpy as np |
| 39 |
import io |
| 40 |
|
| 41 |
t = np.arange(0.0, 2.0, 0.01) |
| 42 |
s = 1 + np.sin(2 * np.pi * t) |
| 43 |
|
| 44 |
fig, ax = plt.subplots(figsize=(5, 3.5)) |
| 45 |
ax.plot(t, s) |
| 46 |
|
| 47 |
ax.set(xlabel='time (s)', ylabel='voltage (mV)', |
| 48 |
title='About as simple as it gets, folks') |
| 49 |
ax.grid() |
| 50 |
|
| 51 |
with io.StringIO() as file: # save to "in-memory file" |
| 52 |
fig.savefig(file, format='pgf', bbox_inches='tight', pad_inches=0.1) |
| 53 |
print(file.getvalue()) |
| 54 |
\end{python} |
| 55 |
\end{center} |
| 56 |
|
| 57 |
For an alternative approach to creating plots with \emph{matplotlib}, |
| 58 |
consider the example \verb|matplotlib-external.tex|. |
| 59 |
|
| 60 |
\end{document} |