How to Export Matplotlib Plot with Transparent Background in Python?
In this article, we will discuss how to export a Matplotlib plot with Transparent background in Python.
After plotting the data, if we want to export the plot, then we have to use savefig() function.
Syntax:
savefig('plot_name.png', transparent=True)where
- plot_name is the image name given to our plot which is plotted from the data
- transparent is used to get the transparent background when it set to true
Example 1: Python code to create the plot with 2 data points of the dataframe and export it
Python3
#import matplotlibimport matplotlib.pyplot as plt #import pandasimport pandas as pd # create a dataframe with 2 columnsdata = pd.DataFrame({'data1': [1, 2, 3, 4, 21], 'data2': [6, 7, 8, 9, 10]}) # plot one by oneplt.plot(data['data1']) plt.plot(data['data2']) # set y labelplt.ylabel('Distance') # set x labelplt.xlabel('Time') # set titleplt.title('Travelling') # display plotplt.show() # export itplt.savefig('image.png', transparent=True) |
Output:
Example 2 : Python code to create the plot with 3 data points of the dataframe and export it
Python3
#import matplotlibimport matplotlib.pyplot as plt #import pandasimport pandas as pd # create a dataframe with 2 columnsdata = pd.DataFrame({'data1': [1, 2, 3, 4, 21], 'data2': [6, 7, 8, 9, 10], 'data3': [56, 7, 8, 41, 10]}) # plot one by oneplt.plot(data['data1'])plt.plot(data['data2'])plt.plot(data['data3']) # set y labelplt.ylabel('Distance') # set x labelplt.xlabel('Time') # set titleplt.title('Travelling') # display plotplt.show() # export itplt.savefig('image.png', transparent=True) |
Output:



