Open In App

Saving a Plot as an Image in Python

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes we want to save charts and graphs as images or even images as a file on disk for use in presentations to present reports. And in some cases, we need to prevent the plot and images for future use. In this article, we’ll see a way to save a plot as an image by converting it to an image, and we’ll also see how to use the save file feature in some of the most popular data visualizations and plotting Python libraries to save plots as an image.

Saving a plot as an image by converting it to a PIL Image in Python

Below are some approaches which we followed to Save a Plot as an Image.

  • Importing necessary library for plotting.
  • Creating a list or loading data for plotting a line graph 
  • Plotting line Graph with the created list or load data.
  • Create a Function for Converting a passed figure to a PIL Image.
  • Save the return image in a variable by passing a plot in the created function for Converting a plot to a PIL Image.
  • Save the image with the help of the save() Function.

Python3




# Importing necessary library for plotting.
import numpy as np
import matplotlib.pyplot as plt
import io
from PIL import Image
  
# Creating list of Month and Share_buy for Plotting Line Graph
Month = ['January', 'February', 'March']
Share_buy = [10, 17, 30]
  
# Plotting Line Graph
plt.title("Share's Buy in a month")
plt.xlabel('Months')
plt.ylabel("No of Share's")
plt.plot(Month, Share_buy)
  
# Getting the current figure and save it in the variable.
fig = plt.gcf()
  
# Create a Function for Converting a figure to a PIL Image.
  
  
def fig2img(fig):
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = Image.open(buf)
    return img
  
  
# Save return image in a variable by passing
# plot in the created function for Converting a plot to a PIL Image.
img = fig2img(fig)
  
# Save image with the help of save() Function.
img.save('Plot image.png')


Output File:

Saving a Plot as an Image in Python

Saved Plot as an Image in Python

Saving a Matplotlib Plot as an Image in Python

Below are some approaches which we followed to Save a Plot as an Image.

  • Importing necessary libraries for plotting like Matplotlib.
  • Creating a list or loading data for plotting a line graph 
  • Plotting line Graph with the created list or load data.
  • Saving a plot on disk as an image file with the help of Matplotlib ‘savefig( )‘ function.

Python3




# Importing library
import matplotlib.pyplot as plt
  
# Creating list of Month and Share_buy for Plotting Line Graph
Month = ['January', 'February', 'March']
Share_buy = [10, 17, 30]
  
# Plotting Line Graph
plt.title("Share's Buy in a month")
plt.xlabel('Months')
plt.ylabel("No of Share's")
plt.plot(Month, Share_buy)
  
# Saving a plotted graph as an Image
plt.savefig('plot image.png')
plt.show()


Output:

Saving a Plot as an Image in Python

Line Chart using Matplotlib

Output File:

Saved Plot as an Image in Python

Saved Plot as an Image in Python

Saving a Seaborn Plot as an Image in Python

Below are some approaches which we followed to Save a Plot as an Image.

  • Importing necessary library for plotting like seaborn.
  • Creating a list or load data for plotting a Scatter Plot
  • Plotting Scatter plot with the loaded data.
  • Saving a plot on disk as an image file with the help of ‘savefig( )‘ function.

Python3




# Importing necessary library for plotting.
import seaborn as sns
  
# load the inbuilt 'iris' dataset using seaborn inbuilt function load_dataset
data = sns.load_dataset('iris')
  
# Plotting scatter plot
scatter_plot = sns.scatterplot(x=data['sepal_length'],
                               y=data['petal_length'],
                               hue=data['species'])
  
# use get_figure function and store the plot in a variable (scatter_fig)
scatter_fig = scatter_plot.get_figure()
  
# use savefig function to save the plot and give a desired name to the plot.
scatter_fig.savefig('Seaborn scatterplot.png')


Output:

Scatter Plot using Seaborn

Scatter Plot using Seaborn

Output File:

Saved Plot as an Image in Python

Saved Plot as an Image in Python

Saving a Plotly Plot as an Image in Python

Note: In plotly Static image generation requires Kaleido library. So to save plotly plot as an image, install Kaleido library in your system.

Below are some approaches which we followed to Save a Plot as an Image.

  • Importing necessary library for plotting like plotly.
  • Creating a list or loading data for plotting a line graph 
  • Plotting line Graph with the created list or load data.
  • Saving a plotly plot on disk as an image file with the help of the ‘write_image()‘ function.

Python3




# Importing library
import plotly.express as px
  
# Creating list of Month and Share_buy for Plotting Line Graph
Month = ['January', 'February', 'March']
Share_buy = [10, 17, 30]
  
# Plotting line Graph with the created list or loaded data.
fig = px.line(x=Month, y=Share_buy, title="Share's Buy in a month")
  
# Saving a plotly plot on disk as an image file
# with the help of 'write_image()' function.
fig.write_image("plotly plot.png")
fig.show()


Output:

 

Output File:

Saving a Plot as an Image in Python

Saved Plot as an Image in Python

Saving an Interactive Plot as an Image in Python

There are times when we create 3D visualizations then it requires interactive features to carefully analyze the graph. To enable these features in the Matplotlib library then we will have to add inline magic in the python code that is %matplotlib notebook after adding this the graph which is created have different options to save, zoom and focus on a selected rectangular area.

Python3




# creating 3d bar plot using matplotlib
# in python to interacte with plot
  
%matplotlib notebook
# importing required libraries
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
# creating random dataset
xs = [2, 3, 4, 5, 1, 6, 2, 1, 7, 2]
ys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
zs = np.zeros(10)
dx = np.ones(10)
dy = np.ones(10)
dz = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# creating figure
figg = plt.figure()
ax = figg.add_subplot(111, projection='3d')
# creating the plot
plot_geeks = ax.bar3d(xs, ys, zs, dx,
                    dy, dz, color='green')
# setting title and labels
ax.set_title("3D bar plot")
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
plt.savefig('my_plot1.png')
plt.close()


Output:

 

In the above interactive plot, there is an option there to download the image, and hence using this we can download or save an interactive plot in Python. Instead of using plt.show() if we will use plt.close() then this interactive feature of the plot will disappear automatically.

 



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

Similar Reads