Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
matplotlib

Figure size, aspect ratio, and dpi of a matplotlib figure

Educative Team

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 figsize argument in the figure function allows us to specify two things:
    • Figure size: The width and height are the actual size of the image in inches.
    • Aspect ratio: The ratio of width and heightwidth:height—specifies the aspect ratio of the image.
  • The dpi argument in the figure function 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:

#imports
import matplotlib.pyplot as plt
import numpy as np
#input data
y = np.array([12, 13, 25, 8, 42])
mylabels = ["Category A", "Category B", "Category C", "Category D", "Category E"]
#figure and chart
plt.figure(figsize=(5,4), dpi=25)
plt.pie(y, labels = mylabels)
plt.show() 
Display a figure and see that we can change the properties of the figure in the code

Explanation

  • Lines 2–3: We import the numpy and matplotlib.pyplot libraries.
  • Lines 5–6: We specify the data we want to display in our figure.
  • Line 8: We specify the properties that we want our figure to have. The width of the image is set to 5, the height is 4, the aspect ratio is 5:4 (width to height ratio), and the dpi is set to 25.
  • Line 9: We specify we want to display a pie chart using the array y. The labels for our categories have been specified in labels.
  • Line 10: This command shows our desired image as a pop up.

RELATED TAGS

python
matplotlib
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring