Matplotlib Generate PGF File: Create a PGF Plot – Matplotlib Tutorial

By | November 23, 2020

If you plan to insert an image to latex, you can insert a pgf or eps image. In this tutorial, we will introduce how to use matplotlib to create a pgf file for latex.

Preliminary

You should import matplot and use pgf.

import matplotlib
matplotlib.use("pgf")
import matplotlib.pyplot as plt

You should notice: You must use matplotlib.use(“pgf”) before importing plt.

Set some parameters for latex

In order to make your plot is adaptive for latex, you should make some parameters for your plot. Here is an example:

matplotlib.rcParams.update({
    "pgf.texsystem": "pdflatex",
    'font.family': 'serif',
    'text.usetex': True,
    'pgf.rcfonts': False,
})

Start draw plot and save to pgf file

Then we can start to create a plot using matplotlib. Here is an example:

x = [1,2,3,4,5]
y = x

fig = plt.figure()
fig.set_size_inches(w=4.7747, h=3.5)

plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
plt.plot(x, y, '-o')
plt.grid(linestyle="--")                   
plt.xlabel("Time/s",fontsize=7.5)
plt.ylabel("Angle/(°)",fontsize=7.5)
#plt.show()
plt.savefig('test.pgf')

In this example, we have created a test.pgf file, which contains our plot.

Matplotlib Generate PGF File - Create a PGF Plot - Matplotlib Tutorial

Then we can insert this test.pgf to your latex.

Leave a Reply

Your email address will not be published. Required fields are marked *