简体   繁体   English

从 Jupyter Notebook 显示和保存 PGF 图

[英]Showing and saving PGF plots from Jupyter Notebook

I have prepared a Jupyter Notebook with a number of matplotlib plots.我准备了一个带有许多 matplotlib 图的 Jupyter Notebook。 Now I would like to save plots to PGF format, so I can reuse them in LaTeX.现在我想将绘图保存为 PGF 格式,以便我可以在 LaTeX 中重用它们。 I have followed this blog post to implement that idea.我已经按照 这篇博客文章来实现这个想法。

Unfortunately, if I configure matplotlib to generate PGF files they are not shown in the notebook.不幸的是,如果我配置 matplotlib 来生成 PGF 文件,它们不会显示在笔记本中。 If I disable matplotlib to generate PGF files plots are shown but PGF files are not generated.如果我禁用 matplotlib 来生成 PGF 文件,则会显示图,但不会生成 PGF 文件。 How can I have both?我怎么能两者兼得?

Here's minimal example to reproduce the problem:这是重现问题的最小示例:

# 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')

Here's the output for enabled configuration of matplotlib.这是启用matplotlib 配置的输出。 histogram.pgf file is generated and saved, but plot is not shown.生成并保存histogram.pgf文件,但未显示绘图。

启用配置

Here's example of when disabling matplotlib configuration for PGF.这是禁用 PGF 的 matplotlib 配置时的示例。 Plot is shown, but generated histogram.pgf file is empty --- does not contain the plot.显示了绘图,但生成的histogram.pgf文件为空 --- 不包含绘图。

在此处输入图片说明

I cannot reproduce your problem我无法重现您的问题

在此处输入图片说明

在此处输入图片说明

I had to run the first cell three or four times, otherwise I wouldn't see the figure.我不得不运行第一个单元三四次,否则我看不到图。

%matplotlib inline

By the way, I am using Ubuntu 16.04, with Python 3.7.6 and Matplotlib 3.1.1.顺便说一下,我使用的是 Ubuntu 16.04,以及 Python 3.7.6 和 Matplotlib 3.1.1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM