How to Use of pyplot.figure() in Matplotlib
-
Use
matplotlib.pyplot.figure()
to Set the Figure Properties -
Use
matplotlib.pyplot.figure()
to Add Subplots to a Figure
This tutorial explains how we can use matplotlib.pyplot.figure()
to change a Matplotlib figure’s various properties. A matplotlib figure is simply a top-level container of all the axes and properties of a plot. To know more about the details of a Matplotlib figure, you can refer to the official documentation page.
Use matplotlib.pyplot.figure()
to Set the Figure Properties
matplotlib.pyplot.figure(num=None,
figsize=None,
dpi=None,
facecolor=None,
edgecolor=None,
frameon=True,
FigureClass= < class 'matplotlib.figure.Figure' > ,
clear=False,
**kwargs)
We can use the matplotlib.pyplot.figure()
to create a new figure and set values of various parameters to customize the plot like figsize
, dpi
, and much more.
Example: Use matplotlib.pyplot.figure()
to Set the Figure Properties
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [4, 3, 5, 6, 7, 4]
plt.figure(figsize=(8, 6), facecolor="yellow")
plt.plot(x, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.title("Plot with figsize (8,6)")
plt.show()
Output:
It creates the figure object and sets the figure’s width to 8 inches and the figure’s height to 6 inches. The face color is set to be yellow.
Use matplotlib.pyplot.figure()
to Add Subplots to a Figure
The matplotlib.pyplot.figure()
returns a figure object which can be used to add subplots
to the figure using the add_subplot()
method.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5, 6]
y = [4, 3, 5, 6, 7, 4]
fig = plt.figure()
subplot1 = fig.add_subplot(2, 1, 1)
subplot1.plot(x, y)
subplot2 = fig.add_subplot(2, 1, 2)
subplot2.text(0.3, 0.5, "2nd Subplot")
fig.suptitle("Add subplots to a figure")
plt.show()
Output:
It adds two subplots to the figure object fig
created using the matplotlib.pyplot.figure()
method.
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn