typestar

Saving figures in Python

The format follows the extension; dpi and bbox decide the rest.

import matplotlib

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

figure, axes = plt.subplots(figsize=(4, 2.5))
axes.plot([1, 2, 3], [3, 1, 2])
axes.set_title("saved three ways")

figure.savefig("plot.png", dpi=200, bbox_inches="tight")
figure.savefig("plot.svg")
figure.savefig("plot.pdf", transparent=True)
plt.close(figure)
print(plt.get_fignums())

How it works

  1. bbox_inches=\u0022tight\u0022 crops the whitespace away.
  2. transparent=True drops the background for slides.
  3. Close the figure when you are done, or memory grows.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
359
Tokens
112
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 4 of 4 in Figures & axes, step 4 of 14 in Plotting with matplotlib.

← Previous Next →