Python Matplotlib Tutorial

Matplotlib savefig – Matplotlib Save Figure | Python matplotlib Tutorial

Matplotlib Save Figure

After creating a plot or chart using the python matplotlib library and need to save and use it further. Then the matplotlib savefig function will help you. In this blog, we are explaining, how to save a figure using matplotlib?

Import Library

import matplotlib.pyplot as plt # for data visualization 

Matplotlib SaveFig (save figure) Different ways

Syntax: plt.savefig(

                                   “File path with name or name”,
                                   dpi=None,
                                   quality = 99,
                                   facecolor=’w’,
                                   edgecolor=’w’,
                                   orientation=’portrait’,
                                   papertype=None,
                                   format=None,
                                   transparent=False,
                                   bbox_inches=None,
                                   pad_inches=0.1,
                                   frameon=None,
                                   metadata=None,

                                   )

Recommended Value Type for Parameters 

fname : str or file-like object
dpi : [ *None* | scalar > 0 | ‘figure’ ]quality : [ *None* | 1 <= scalar <= 100 ]
facecolor : color spec or None, optional
edgecolor : color spec or None, optional
orientation : {‘landscape’, ‘portrait’}
papertype : str
— ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through
‘a10’, ‘b0’ through ‘b10’
format : str —png, pdf, ps, eps and svg
transparent : bool
frameon : bool
bbox_inches : str or `~matplotlib.transforms.Bbox`, optional
pad_inches : scalar, optional
bbox_extra_artists : list of `~matplotlib.artist.Artist`, optional
metadata : dict, optional

Here, we are creating a simple pie chart and save it using plt.savefig() function. The file saves at program file location by default with “.png” format. You can change the file path. 

plt.pie([40,30,20]) # plot pie chart
plt.savefig("pie_char") # save above pie chart with name pie_chart
plt.show()

Output >>>

Pie Chart

Saved Image >>>

Matplotlib Savefig
pie_chart.png

Save Matplolib Figure using some parameters

plt.pie([40,30,20])
plt.savefig("pie_char2", # file name
            dpi = 100,  # dot per inch for resolution increase value for more resolution
            quality = 99, # "1 <= value <= 100" 100 for best qulity
            facecolor = "g" # image background color
           )
plt.show()

Output >>>

Pie Chart

Saved Image >>>

Matplotlib Savefig with parameters
pie_chart2.png

Example:

In bellow example, create plots and charts and show using subplot function. Then line no. “105(plt.savefig(“D:\\subplot_figure.png”)) save this subplot at user define location.

plt.figure(figsize=(23,27))

##----------------------------------------start 
#plt.subplot(3,2,1)
plt.subplot(321)
#********************************************Line Plot
days = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
delhi_tem = [36.6, 37, 37.7,39,40.1,43,43.4,45,45.6,40.1,44,45,46.8,47,47.8]
mumbai_tem = [39,39.4,40,40.7,41,42.5,43.5,44,44.9,44,45,45.1,46,47,46]

plt.plot(days, delhi_tem, "mo--", linewidth = 3,
        markersize = 10, label = "Delhi tem")

plt.plot(days, mumbai_tem, "yo:", linewidth = 3,
        markersize = 10, label = "Mumbai tem}")

plt.title("Delhi  & Mumbai Temperature Line Plot", fontsize=15)
plt.xlabel("days",fontsize=13)
plt.ylabel("temperature",fontsize=13)
plt.legend(loc = 4)
plt.grid(color='w', linestyle='-', linewidth=2)

#---------------------------------------------------------------end

plt.subplot(3,2,2) ##-------------------------------------------------start
#****************************************************************histograms
ml_students_age = np.random.randint(18,45, (100))
py_students_age = np.random.randint(15,40, (100))
bins = [15,20,25,30,35,40,45]

plt.hist([ml_students_age, py_students_age], bins, rwidth=0.8, histtype = "bar",
         orientation='vertical', color = ["m", "y"], label = ["ML Student", "Py Student"])

plt.title("ML & Py Students age histograms")
plt.xlabel("Students age cotegory")
plt.ylabel("No. Students age")
plt.legend()
#----------------------------------------------------------------------end

plt.subplot(3,2,3) ##--------------------------------------------start
#************************************************************Bar Chart
classes = ["Python", "R", "AI", "ML", "DS"]
class1_students = [30, 10, 20, 25, 10] # out of 100 student in each class
class2_students = [40, 5, 20, 20, 10]
class3_students = [35, 5, 30, 15, 15]
classes_index = np.arange(len(classes))

width = 0.2

plt.barh(classes_index, class1_students, width , color = "b",
        label =" Class 1 Students") #visible=False

plt.barh(classes_index + width, class2_students, width , color = "g",
        label =" Class 2 Students") 

plt.barh(classes_index + width + width, class3_students, width , color = "y",
        label =" Class 3 Students") 

plt.yticks(classes_index + width, classes, rotation = 20)
plt.title("Bar Chart of IAIP Class Bar Chart", fontsize = 18)
plt.ylabel("Classes",fontsize = 15)
plt.xlabel("No. of Students", fontsize = 15)
plt.legend()
#--------------------------------------------------------------------end

plt.subplot(3,2,4) ##------------------------------------------------start
#**************************************************************Scatter Plot
df_google_play_store_apps = pd.read_csv("D:\\Private\Indina AI Production\Kaggel Dataset\google-play-store-apps\googleplaystore.csv", nrows = 1000)
x = df_google_play_store_apps["Rating"]
y = df_google_play_store_apps["Reviews"]
plt.scatter(x,y, c = "r", marker = "*", s = 100, alpha=0.5, linewidths=10,
           edgecolors="g" )#verts="<"

plt.scatter(x,df_google_play_store_apps["Installs"], c = "y", marker = "o", s = 100, alpha=0.5, linewidths=10,
           edgecolors="c" )
plt.title("Google Play Store Apps Scatter plot")
plt.xlabel("Rating")
plt.ylabel("Reviews & Installs")
#----------------------------------------------------------------------end


plt.subplot(3,2,5) ##-----------------------------------------start
#*************************************************************Pie plot
classes = ["Python", 'R', 'Machine Learning', 'Artificial Intelligence', 
           'Data Sciece']
class1_students = [45, 15, 35, 25, 30]
explode = [0.03,0,0.1,0,0]
colors = ["c", 'b','r','y','g']
textprops = {"fontsize":15}

plt.pie(class1_students, 
        labels = classes, 
        explode = explode, 
        colors =colors, 
        autopct = "%0.2f%%", 
        shadow = True, 
        radius = 1.4,
       startangle = 270, 
        textprops =textprops)
#------------------------------------------------------end


plt.subplot(3,2,6, projection='polar', facecolor='k' ,frameon=True)

plt.savefig("D:\\subplot_figure.png") # save subplots at drive "D" of name subplot_figure
plt.show()

Output >>>

Matplotlib Subplots

Saved Image >>>

Matplotlib Savefig - subplots
subplot_figure.png

CONCLUSION

In the matplotlib save figure blog, we learn how to save figure with a real-time example using the plt.savefig() function. Along with that used different method and different parameter. We suggest you make your hand dirty with each and every parameter of the above methods. This is the best coding practice. After completion of the matplotlib tutorial jump on Seaborn.

Download Jupyter file of matplotlib savefig source code

Visit the official site of matplotlib.org

Leave a Reply