How to Export Matplotlib Plot with Transparent Background


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

Leave a Reply

Your email address will not be published.