The default background for matplotlib plots is white, you can change the background colors of the plot, and you can also save your plots with a transparent background. In this tutorial, we’ll look at how to save a matplotlib figure as a PNG image with a transparent background.
Export matplotlib image with a transparent background
The matplotlib pyplot’s savefig()
function is used to save a plot as a file. You can use the transparent
argument to specify whether or not you want a transparent background for your saved image. The following is the syntax:
plt.savefig("filename.png", transparent=True)
The above syntax assumes that “matplotlib.pyplot” is imported as “plt”. Note that the default value of the transparent
argument is False
.
Examples
Let’s look at some examples to illustrate the usage of the above syntax.
1. Saving a plot with its default background
Let’s create a sample line chart in matplotlib and save it as an image file without explicitly passing a value to the transparent
keyword. The below code creates a line chart of year-on-year employee growth at a company.
import matplotlib.pyplot as plt # employee growth year over year emp_count = [3, 20, 50, 200, 350, 400] year = [2014, 2015, 2016, 2017, 2018, 2019] # plot the employee growth plt.plot(year, emp_count) # add axes labels and plot title plt.xlabel('Year') plt.ylabel('Employees') plt.title("Employee Growth YoY") # save the plot as a PNG image plt.savefig("employee_growth.png")
This is how the above saved image looks if we place it over a colored background.

You can see that the plot has its own white background, over and above the colored background.
2. Saving a plot with transparent background
Now let’s go ahead and plot the same line plot but this time we’ll save it with a transparent background.
# plot the employee growth plt.plot(year, emp_count) # add axes labels and plot title plt.xlabel('Year') plt.ylabel('Employees') plt.title("Employee Growth YoY") # save the plot as a PNG image with Transparent background plt.savefig("employee_growth_tp.png", transparent=True)
This is how the above saved image looks if we place it over a colored background.

You can notice that this image easily blends in with the colored background since it’s transparent.
For more on the matploblib’s savefig() function, refer to its documentation.
With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having matplotlib version 3.2.2
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.