11.1 C
London
Sunday, July 7, 2024
HomePythonMatplotlib in PythonHow to Export Matplotlib Plot with Transparent Background

How to Export Matplotlib Plot with Transparent Background

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following basic syntax to export a Matplotlib plot with a transparent background:

savefig('my_plot.png', transparent=True)

Note that the default argument for savefig() is transparent=False.

By specifying transparent=True we can save a Matplotlib figure with a transparent background.

The following example shows how to use this syntax in practice.

Example: Export Matplotlib Plot with Transparent Background

The following code shows how to create a line plot in Matplotlib and save the plot with a transparent background:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10, 15]
y = [5, 7, 21, 22]

#create line plot
plt.plot(x, y)

#add title and axis labels
plt.title('Title of Plot')
plt.xlabel('X Label')
plt.ylabel('Y Label')

#save plot with transparent background
plt.savefig('my_plot.png', transparent=True)

If I navigate to the location on my computer where the image is saved, I can view it:

However, this doesn’t illustrate the transparent background well.

To do so, I can place the image on a colored background in Excel:

Notice that the background is completely transparent.

You can contrast this with the exact same image saved without using the transparent argument:

#save plot without specifying transparent background
plt.savefig('my_plot2.png')

The background is white, which is the default background color in Matplotlib.

Note: You can find the complete online documentation for the savefig() function here.

Additional Resources

The following tutorials explain how to perform other common operations in Matplotlib:

How to Save Matplotlib Figure to a File
How to Increase Plot Size in Matplotlib
How to Create Multiple Matplotlib Plots in One Figure

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories