In this Python tutorial, we will discuss Matplotlib save as png in python. Here we will cover different examples related to saving images as png using matplotlib. And we will also cover the following topics:
- Matplotlib how to save as png
- Matplotlib save as png
- Matplotlib save as png dpi
- Matplotlib graph as png
- Matplotlib save png transparent background
- Matplotlib save png change background
- Matplotlib save png without border
- Matplotlib save array as png
- Matplotlib save axis as png
- Matplotlib save figure as png size
- Matplotlib save chart as png
- Matplotlib save figure as png with high resolution
- Matplotlib save as png edgecolor
If you are new to Matplotlib, check out What is Matplotlib and how to use it in Python and also, How to install matplotlib python
Matplotlib how to save as png
In this section, we are going to learn about how we save a plot or graph as an image file by using the matplotlib library. Firstly, we discuss what does “png” mean:
PNG stands for Portable Network Graphics
PNG is a compressor used to compressed images into smaller sizes without losing their details.
The following steps are used to save plot or graph as png are outlined below:
- Defining Libraries: Import the important libraries which are required to save image as png and to define data (For data creation and manipulation: Numpy, For data visualization: pyplot from matplotlib).
- Define X and Y: Define the data values used for the x-axis and y-axis.
- Create a pLot: By using plot() method create a plot or you can use any other method which ever you like.
- Save as png: By using savefig() method you can save image into your system. Set extension of the file to “png” as your main aim is to save as png.
- Generate Plot: By suing show() function, generate a plot to the user.
Note: Use savefig() method before show() method.
Matplotlib save as png
To save a plot or graph or a figure as png we use the savefig() method. The objective of this method is to save images to your local system memory.
The syntax of the savefig() method is as below:
matplotlib.pyplot.savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
The parameters used are discussed as below:
- fname: specifies file name or file location.
- dpi: specifies picture quality (No. of dots per inch).
- facecolor: specifies facecolor of the image as per your choice. By default, it is “White”.
- edgecolor: specifies edgecolor of the plot as per your choice. By default, it is “White”.
- orientation: You can set the orientation of the image as Landscape or Portrait.
- papertype: specifies the type of paper such as “letter”, “legal” “a0 to a10”, etc.
- format: specifies the extension of the file such as .png.
- transparent: to make the background of the image transparent.
- bbox_inches: specifies the portion of the image to save. For a proper fitting set, it to “tight”.
- pand_inches: specifies padding around the image when bbox_inches is “tight”.
- metadata: specifies key/value pair to store in the image metadata. Take data in the dict datatype.
Let’s see an example of save as png:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x= [1, 2, 3, 4, 5]
y= [2.5, 6.3, 12, 14, 2]
# Plot
plt.plot(x,y,color='r')
# Save image as png
plt.savefig('save as png.png')
# Show image
plt.show()
- In the above example, firstly we import matplotlib.pyplot library. After this, we define data in x and y coordinates.
- plot() function is used to plot a graph.
- Once the plot is generated, we use the savefig() method to save figures in our projects directory.
- After that use show() method which is used to generate a plot for the user in a window.
Read: Matplotlib plot a line
Matplotlib save as png dpi
The “dpi” argument decides the number of dots. The dot’s values are defined in pixels.
The syntax is as given below:
matplotlib.pyplot.savefig(fname, dpi=None)
Let’s see an example without dpi so we get difference:
# Import Library
import matplotlib.pyplot as plt
# Define Data
student = [3,2,0,5,9,1]
weight = [30,35,40,45,50,55]
# Plot Graph
plt.scatter(weight,student)
# Define axes label
plt.xlabel("Weight of the students")
plt.ylabel("Number of students")
# Save image
plt.savefig('save as png without dpi.png')
# Display Graph
plt.show()
Let’s see an example where we save the image with dpi:
# Import Library
import matplotlib.pyplot as plt
# Define Data
student = [3,2,0,5,9,1]
weight = [30,35,40,45,50,55]
# Plot Graph
plt.scatter(weight,student)
# Define axes label
plt.xlabel("Weight of the students")
plt.ylabel("Number of students")
# Save image
plt.savefig('save as png dpi.png', dpi = 150)
# Display Graph
plt.show()
Read: What is matplotlib inline
Matplotlib graph as png
In this section, we are going to learn how we can save bar graphs as png. For this firstly, you have to plot the bar chart and after that save it in png form.
The syntax is as below:
# Plot graph
matplotlib.pyplot.bar(x,y)
# Save as png
matplotlib.pyplot.savefig(fname)
Let’s see an example related to this:
# Import Library
import matplotlib.pyplot as plt
# Define Data
students = [5, 6, 2, 3]
activities= ["Joging", "Gyming", "Swimming", "Shopping"]
# Plot bar chart
plt.bar( activities, students, color= 'm')
# Save image
plt.savefig('save graph as png.png', dpi =100)
# Display chart
plt.show()
In the above, we plot the bar chart by using the plt.bar() method and after that we use plt.savefig() method to save image as png we also set its dpi value to 100.
Read: Python plot multiple lines using Matplotlib
Matplotlib save png transparent background
Here we will learn how to save images with transparent backgrounds. We will use a savefig() function to save the plot as an image and we pass the transparent as an argument, set its value to True.
Example: Plot having pink background color and we save the image without Transparent argument.
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0, 5, 0.2)
y = np.cos(x)
# Plot figure and set background to pink
ax = plt.figure()
ax.set_facecolor('pink')
plt.plot(x, y)
# Save image
plt.savefig('save png without transparent background.png')
# Generate Plot
plt.show()
- In the above example, we plot a graph and save it by using the savefig() method.
- We also set background color of the plot to pink.
Example: Plot having pink background color and we save the image with Transparent argument.
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0, 5, 0.2)
y = np.cos(x)
# Plot figure and set background to pink
ax = plt.figure()
ax.set_facecolor('pink')
plt.plot(x, y)
# Save image
plt.savefig('save png transparent background.png', transparent = True)
# Generate Plot
plt.show()
Read: Matplotlib plot bar chart
Matplotlib save png change background
Here we learn how we change the face color of the plot. By default, the face color is “White”.
We can change it by passing the facecolor argument to the savefig() method.
Syntax to change facecolor is as given below:
matplotlib.pyplot.savefig(fname, facecolor = None)
Example:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
# Plot
plt.plot(x, y)
# Save image
plt.savefig('save png change background.png', facecolor ='orange')
# Generate Plot
plt.show()
In this above example, we use the savefig() method to save a figure as an image and we pass the facecolor argument to it and set its value to “orange”.
Read: Matplotlib subplot tutorial
Matplotlib save png without border
When we pass the bbox_inches argument to savefig() method and set its value to “tight”, it removes its border.
Basically, it crops the extra border from the figure as much as possible.
The syntax to remove extra border:
matplotlib.pyplot.savefig(fname, bbox_inches='tight')
Let’s see an example of save as png without border:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = [1, 2, 3, 4, 5]
y = [1, 2, 3, 4, 5]
# Plot
plt.scatter(x, y)
# Save image
plt.savefig('save png without border.png', facecolor ='green', bbox_inches='tight')
# Generate Plot
plt.show()
In this above example, we set the facecolor to green and we also use the bbox_inches argument to cut its extra border.
Read: Matplotlib best fit line
Matplotlib save array as png
To save the array as png image we use the imsave() method.
The syntax is as given below:
mtplotlib.pyplot.imsave(fname, array)
Example:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0, 737280, 1, np.uint8)
array = np.reshape(array, (1024, 720))
# Save image
plt.imsave('save array as png.png', array)
# Show plot
plt.show()
In the above example, we use the imsave() method to save the array as an image.
Read: Matplotlib subplots_adjust
Matplotlib save axis as png
Here we see how we save axes as png.
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
# Define Data
x = [1, 2, 3, 4, 5]
y = [1, 2, 15, 4, 5]
# Define axes
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Save image
plt.savefig('matplotlib save axis as png.png', bbox_inches='tight')
# Generate Plot
plt.show()
In the above example, we only plot the axes of the graph.
Read: Matplotlib plot_date
Matplotlib save figure as png size
By using the dpi argument we can increase and decrease the size of the figure as per your choice.
The syntax is as below:
matplotlib.pyplot.savefig(fname, dpi=None)
Let’s see an example:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
x = np.arange(0, 5, 0.2)
y = np.sin(x)
# Plot figure
plt.plot(x, y)
# Save image
plt.savefig('save figure as png size.png', dpi=30)
# Generate Plot
plt.show()
Here we set the size of the dpi argument to 30 and pass it to the savefig() method.
Read: Matplotlib dashed line
Matplotlib save chart as png
Here we learn how we can save the pie chart as an image. Firstly, you have to know how to create a pie chart.
The syntax to plot a pie chart and save it as an image is as below:
# Pie chart
matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, autopct=None, shadow=False)
# Save Image
matplotlib.pyplot.savefig(fname)
The parameters used above are defined as:
- data: specifies the array of data values to be plotted.
- labels: specifies labels to each wedge.
- color: specifies color of the wedges.
- autopct: used to label the wedge with the numerical values.
- shadow: used to create a shadow.
- fname: file name or path
Example:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data
subjects = ['MATHS', 'SCIENCE', 'ENGLISH', 'HINDI', 'SOCIAL-SCIENCE']
data = [20, 7, 31, 25, 12]
# Creating plot
plt.pie(data, labels = subjects)
# save as an image
plt.savefig('save chart as png.png')
# show plot
plt.show()
- In the above example, we first import the matplotlib.pyplot and numpy library.
- After that, we define the data and labels and plot a pie chart by using the pie() method.
- Then we use plt.savefig() method to save pie chart as an image in png form.
- Lastly, we use the show() method to visualize the chart.
Read: Matplotlib scatter marker
Matplotlib save figure as png with high resolution
To save a figure with a high resolution you have to pass a dpi argument in the savefig() method and increase its value.
Let’s see an example of a high-resolution figure:
# Import Library
import matplotlib.pyplot as plt
# Define Data
student = [15, 12, 10, 5, 2]
marks = [50, 45, 30, 22, 15]
# Plot Graph
plt.bar(marks,student)
# Define axes label
plt.xlabel("Marks of the students")
plt.ylabel("Number of students")
# Save image
plt.savefig('save figure as png with high resolution.png', dpi=200)
# Display Graph
plt.show()
Read: Matplotlib rotate tick labels
Matplotlib save as png edgecolor
Here we learn how to save a figure with edgecolor in matplotlib.
Programmer sometimes finds it difficult to save the image with edge color because by default linewidth is set to 0.0.
So, to save an image with edge color firstly, you have to change linewidth or we can say that you have to increase line width size.
Syntax to change linewidth and save the image with edge color is as given below:
# Linewidth
matplotlib.pyplot.figure(linewidth= 0.0)
# Save iamge
matplotlib.pyplot.savefig(fname, edgecolor=Name)
Let’s see an example to get a better understand of this concept:
# Import Library
import matplotlib.pyplot as plt
import numpy as np
# Define Data and linewidth
plt.figure(linewidth=15)
x = np.arange(0, 15, 0.2)
y = np.sin(x)
# Plot figure
plt.plot(x, y)
# Save image
plt.savefig('save as png edgecolor.png', edgecolor='blue', facecolor='yellow')
# Generate Plot
plt.show()
- In the above example, firstly we set the linewidth of the figure to 15 and after that, we define the data coordinates.
- Then we use, plt.plot() method to plot the chart and after that, we use the plt.savefig() method to save the plot as an image.
- Here we pass the argument edgecolor and facecolor and set their value to blue and yellow respectively.
You may also like to read the following Matplotlib tutorials.
In this Python tutorial, we have discussed the “Matplotlib save as png” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.
- Matplotlib how to save as png
- Matplotlib save as png
- Matplotlib save as png dpi
- Matplotlib graph as png
- Matplotlib save png transparent background
- Matplotlib save png change background
- Matplotlib save png without border
- Matplotlib save array as png
- Matplotlib save axis as png
- Matplotlib save figure as png size
- Matplotlib save chart as png
- Matplotlib save figure as png with high resolution
- Matplotlib save as png edgecolor
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.