Creating Multiple Plots - ( Matplotlib Subplots and Figures )
Heading h2
Syntax
import matplotlib.pyplot as plt
fig, axs = plt.subplots(nrows, ncols)
Example
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, np.sin(x))
axs[0, 1].plot(x, np.cos(x))
axs[1, 0].plot(x, np.tan(x))
axs[1, 1].plot(x, np.exp(x))
plt.show()
Output
The output of the example code is a figure containing four subplots, each with a different plot.
Explanation
Matplotlib is a widely used Python library for data visualization. It provides various functions for creating different types of plots. plt.subplots()
is a function provided by Matplotlib for creating multiple plots in a single figure.
plt.subplots()
takes in two arguments, nrows
and ncols
, which specify the number of rows and columns of the subplot grid, respectively. The function returns two objects, fig
and axs
. These objects are used to specify properties of the figure and the subplots, respectively.
In the above example, we create a figure with four subplots organized in a 2x2 grid. We plot sine, cosine, tangent, and exponential functions in each of the four subplots.
Use
Creating multiple plots in a single figure is a common requirement in data visualization. Matplotlib provides the functionality to achieve this using plt.subplots()
.
Important Points
plt.subplots()
creates multiple plots in a single figure- The function takes two arguments
nrows
andncols
to specify the number of rows and columns of the subplot grid plt.subplots()
returns two objectsfig
andaxs
which define the figure and subplots- The
axs
object is used to specify properties of the subplots
Summary
In conclusion, creating multiple plots in a single figure is an important requirement in data visualization. Matplotlib provides the plt.subplots()
function for creating subplots in a grid arrangement. The function returns fig
and axs
objects that are used to specify properties of the figure and subplots.