← Back to Pandas Course | Chapter 12: Visualization Basics | Lesson 6 of 6

Saving figures

savefig writes the current figure to a PNG, PDF or SVG file.

In this page:

  1. Saving figures
Syntax
python
import matplotlib.pyplot as plt
df.plot()
plt.savefig("chart.png", dpi=150)
plt.show()

Saving figures

plt.savefig("chart.png", dpi=150) saves the active figure; call it before plt.show, which clears the figure. The format follows the file extension. bbox_inches="tight" trims extra whitespace. Here we save into memory instead of disk.

Note: Use transparent=True for PNGs on coloured backgrounds.

Example: Saving figures

python
import io
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd

ax = pd.Series([1, 3, 2]).plot(title="Demo")
for fmt in ["png", "svg"]:
    buf = io.BytesIO()
    plt.savefig(buf, format=fmt, dpi=100, bbox_inches="tight")
    print(fmt, "saved:", buf.getbuffer().nbytes > 0)

# Output:
# png saved: True
# svg saved: True
Related Topics
Common Mistakes
  1. Calling savefig after show
  2. Low dpi producing blurry images
  3. Cropped labels without bbox_inches
Chapter Summary
  • savefig writes files
  • Format follows the extension
  • dpi sets resolution
  • Call it before show
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.