Matplotlib
| Language | Python |
|---|---|
| License | Matplotlib license (PSF-based, BSD-compatible) |
| Repository | github.com/matplotlib/matplotlib |
| Documentation | savefig, rcParams (ps.*) |
| Depends on | NumPy and others (installed by pip); Ghostscript only for ps.usedistiller |
| Read / write | no / yes (EPS and PostScript) |
Matplotlib’s PostScript backend writes any figure as EPS: call savefig with a .eps file name or format="eps". The figure stays vector (lines, text, markers); images such as imshow output are embedded as bitmaps. Many journals and the latex + dvips route still ask for EPS figures.
PostScript has no transparency: artists with alpha < 1 are drawn opaque and Matplotlib prints a warning. Use PDF or SVG output when you need transparency.
Installation#
Shell
pip install matplotlib
Basic usage: save a chart as EPS#
Python
import matplotlib
matplotlib.use("Agg") # no window needed
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 200)
fig, ax = plt.subplots(figsize=(4, 3)) # inches
ax.plot(x, np.sin(x), label="sin")
ax.plot(x, np.cos(x), label="cos")
ax.set_xlabel("x")
ax.legend()
fig.savefig("plot.eps", bbox_inches="tight") # crop white space
How to embed fonts as TrueType instead of Type 3#
By default text uses Type 3 fonts, which some publishers reject. Type 42 embeds the TrueType font:
Python
import matplotlib.pyplot as plt
plt.rcParams["ps.fonttype"] = 42
fig.savefig("plot.eps")
How to use LaTeX for the text in an EPS figure#
Python
plt.rcParams.update({
"text.usetex": True, # needs a TeX installation
"font.family": "serif",
})
ax.set_title(r"$\int_0^\pi \sin x \, dx = 2$")
fig.savefig("plot.eps")
How to get an exact bounding box#
ps.usedistiller post-processes the file with Ghostscript (or Xpdf), which also recomputes a tight bounding box:
Python
plt.rcParams["ps.usedistiller"] = "ghostscript"
fig.savefig("plot.eps")
How to save as PostScript with a paper size#
Python
fig.savefig("plot.ps", papertype="a4", orientation="portrait")
.ps output is a full page; .eps is cropped to the figure.
Tips#
- Replace transparency with solid colors before saving EPS, for example a light gray instead of black with
alpha=0.2. - Large scatter plots make huge EPS files. Pass
rasterized=Trueto the artist (ax.scatter(..., rasterized=True)) and setdpi=300insavefigto embed that layer as a bitmap.