How to make `matplotlib` generates SVG figures instead of PNG in all my JupyterLab `.ipynb`?
Feb 21, 10:05pm

To make matplotlib generate SVG figures instead of PNG by default in all your JupyterLab .ipynb notebooks, you need to set the default backend and save format in your matplotlib configuration. Here’s how you can do it:


1. Set the Default Backend and Format in Your Notebook

Add the following lines at the beginning of your notebook (or in a cell you run first):

python
%matplotlib inline
import matplotlib.pyplot as plt

# Set the default format to SVG
plt.rcParams['savefig.format'] = 'svg'
plt.rcParams['figure.facecolor'] = 'white'  # Optional: ensures white background
  • %matplotlib inline ensures plots are displayed inline in JupyterLab.
  • plt.rcParams['savefig.format'] = 'svg' sets the default save format to SVG.

2. Save Figures as SVG

When you save a figure using plt.savefig(), it will now default to SVG:

python
plt.plot([1, 2, 3], [4, 5, 6])
plt.savefig('my_plot.svg')  # Will save as SVG

3. (Optional) Make This Permanent for All Notebooks

If you want this setting to apply automatically to all your notebooks, you can add the configuration to your matplotlib config file:

  1. Open or create the file ~/.config/matplotlib/matplotlibrc (Linux/Mac) or C:\Users\<YourUsername>\.matplotlib\matplotlibrc (Windows).
  2. Add the following lines:
    text
    savefig.format: svg
    figure.facecolor: white
  3. Restart JupyterLab.

4. Verify the Output

Run a simple plot and check the file type:

python
plt.plot([1, 2, 3])
plt.savefig('test_plot')  # Should save as test_plot.svg

Why SVG?

  • Scalable: SVG files are vector-based, so they scale perfectly to any size without losing quality.
  • Smaller file size: Often smaller than PNG for simple plots.
  • Editable: You can open and edit SVG files in tools like Inkscape or Illustrator.
Feb 21, 10:05pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.