how to create multiple plots matplotlib in python

To create multiple plots in matplotlib, you can use the subplots function. The subplots function takes as input the number of rows and columns of subplots, and returns a figure and an array of axes objects.

Here's an example:

main.py
import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x = np.arange(0, 10, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)

# Create the subplots
fig, axs = plt.subplots(2, 1)

# Plot the data on each subplot
axs[0].plot(x, y1)
axs[0].set_title('Sin(x)')
axs[1].plot(x, y2)
axs[1].set_title('Cos(x)')

# Show the subplots
plt.show()
339 chars
20 lines

In this example, we generate two arrays of data, y1 and y2, using the numpy library. We then create a figure and an array of two axes objects using the subplots function. We then call the plot function on each of the axes objects to create the plots. Finally, we call the show function to display the subplots.

You can adjust the number of rows and columns of subplots by changing the input to the subplots function. For example, fig, axs = plt.subplots(3, 2) would create a figure with 3 rows and 2 columns of subplots.

related categories

gistlibby LogSnag