Figure size, aspect ratio, and dpi of a matplotlib figure
Overview
The Python matplotlib is a popular open source library, which is used to create customized visualizations including graphs and figures. It allows for specification of the size, aspect ratio, and dpi—dots per inch or pixels per inch—for the matplotlib figure.
Syntax
The code snippet below shows us how to specify the size, aspect ratio, and dpi for our matplotlib figure. All the specifications can be provided in one line.
plt.figure(figsize=(width,height), dpi=pixels_per_inch)
Parameter values
- The
figsizeargument in thefigurefunction allows us to specify two things: - Figure size: The
widthandheightare the actual size of the image in inches. - Aspect ratio: The ratio of
widthandheight—width:height—specifies the aspect ratio of the image. - The
dpiargument in thefigurefunction allows us to specify the pixels per inch that we want in our image.
Return value
When we execute matplotlib.pyplot.show(), or matplotlib.pyplot.savefig(), our figure will have the specified properties.
Example
Let's look at an example:
#importsimport matplotlib.pyplot as pltimport numpy as np#input datay = np.array([12, 13, 25, 8, 42])mylabels = ["Category A", "Category B", "Category C", "Category D", "Category E"]#figure and chartplt.figure(figsize=(5,4), dpi=25)plt.pie(y, labels = mylabels)plt.show()
Explanation
- Lines 2–3: We import the
numpyandmatplotlib.pyplotlibraries. - Lines 5–6: We specify the data we want to display in our
figure. - Line 8: We specify the properties that we want our
figureto have. The width of the image is set to5, the height is4, the aspect ratio is5:4(width to height ratio), and thedpiis set to 25. - Line 9: We specify we want to display a
piechart using the arrayy. The labels for our categories have been specified inlabels. - Line 10: This command shows our desired image as a pop up.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved