Matplotlib is one of the most widely used plotting libraries for Python and is a great choice for creating visualizations of data.
One common requirement when plotting data is to change the size of the figures.
This can be achieved using the figsize parameter in the pyplot.figure function.
In this article, we will learn how to change the size of figures drawn with Matplotlib.
We will also see how to control the aspect ratio of the figure, which is the proportion of width to height.
We will use code examples to illustrate the concepts covered in this article.
Table of Contents
Setting the Figure Size
The figsize parameter is used to specify the size of the figure in inches.
The parameter takes a tuple of two values, which represent the width and height of the figure in inches.
For example, the following code creates a figure with a width of 8 inches and a height of 6 inches:
import matplotlib.pyplot as plt plt.figure(figsize=(8, 6)) plt.plot([1, 2, 3, 4]) plt.show()
Controlling the Aspect Ratio
The aspect ratio of the figure can be controlled using the aspect parameter in the pyplot.axes function.
The aspect parameter takes a value between 0 and 1, where 1 represents a square figure, and values greater than 1 represent figures that are wider than they are tall.
The following code creates a figure with an aspect ratio of 1:
import matplotlib.pyplot as plt plt.figure(figsize=(8, 6)) plt.axes(aspect=1) plt.plot([1, 2, 3, 4]) plt.show()
In conclusion, changing the size and aspect ratio of figures in Matplotlib is simple and can be done using the figsize and aspect parameters in the pyplot.figure and pyplot.axes functions, respectively.
These two parameters allow you to customize the appearance of your figures to suit your needs.