6

我准备了一个带有许多 matplotlib 图的 Jupyter Notebook。现在我想将绘图保存为 PGF 格式,以便在 LaTeX 中重复使用它们。我已经按照这篇博客文章来实现这个想法。

不幸的是,如果我将 matplotlib 配置为生成 PGF 文件,它们不会显示在笔记本中。如果我禁用 matplotlib 来生成 PGF 文件,则会显示绘图,但不会生成 PGF 文件。我怎么能两者兼得?

这是重现问题的最小示例:

# Test if integration between python and latex works fine
import subprocess; subprocess.check_call(["latex", "-help"])

# Configure matplotlib to generate PGF files
import matplotlib
import matplotlib.pyplot as plt 
matplotlib.use("pgf")
matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    'font.family': 'serif',
    'text.usetex': True,
    'pgf.rcfonts': False,
})

# Prepare simple plot
import pandas as pd
df = pd.DataFrame({
     'length': [1.5, 0.5, 1.2, 0.9, 3],
     'width': [0.7, 0.2, 0.15, 0.2, 1.1]
     }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse'])
hist = df.hist(bins=3)

# Save the plot to PGF file
plt.savefig('histogram.pgf')

这是 matplotlib启用配置的输出。histogram.pgf文件已生成并保存,但未显示绘图。

启用配置

这是禁用 PGF 的 matplotlib 配置时的示例。显示了绘图,但生成histogram.pgf的文件为空 --- 不包含绘图。

在此处输入图像描述

4

2 回答 2

0

不要使用matplotlib.use("pgf"); 有一种替代方法可以实现相同的目标,而没有无法显示您的情节的缺点:

from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)

此方法允许您继续使用常规交互式后端,同时能够使用plt.savefig('figure.pdf')1保存已编译的 PDF 文件,并且在文件保存后内联显示绘图。

您仍然可以设置 pgf 参数。无需删除它们,因为它们不会干扰交互式后端:

matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    'pgf.rcfonts': False,
})
于 2021-09-13T05:32:02.243 回答
0

我无法重现您的问题

在此处输入图像描述

在此处输入图像描述

我必须运行第一个单元三四次,否则我看不到这个数字。

%matplotlib inline

顺便说一句,我使用的是 Ubuntu 16.04,带有 Python 3.7.6 和 Matplotlib 3.1.1。

于 2020-01-24T23:49:15.387 回答