Open In App

How to Export Matplotlib Plot with Transparent Background in Python?

Last Updated : 28 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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 matplotlib
import matplotlib.pyplot as plt
  
#import pandas
import pandas as pd
  
# create a dataframe with 2 columns
data = pd.DataFrame({'data1': [1, 2, 3, 4, 21],
                     'data2': [6, 7, 8, 9, 10]})
  
# plot one by one
plt.plot(data['data1'])
  
plt.plot(data['data2'])
  
  
# set y label
plt.ylabel('Distance')
  
# set x label
plt.xlabel('Time')
  
# set title
plt.title('Travelling')
  
# display plot
plt.show()
  
# export it
plt.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 matplotlib
import matplotlib.pyplot as plt
  
#import pandas
import pandas as pd
  
# create a dataframe with 2 columns
data = pd.DataFrame({'data1': [1, 2, 3, 4, 21], 
                     'data2': [6, 7, 8, 9, 10],
                     'data3': [56, 7, 8, 41, 10]})
  
# plot one by one
plt.plot(data['data1'])
plt.plot(data['data2'])
plt.plot(data['data3'])
  
# set y label
plt.ylabel('Distance')
  
# set x label
plt.xlabel('Time')
  
# set title
plt.title('Travelling')
  
# display plot
plt.show()
  
# export it
plt.savefig('image.png', transparent=True)


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads