mutlipel plots python in python

To create multiple plots in Python using matplotlib, we can use the subplots function. This function returns a Figure object and an array of Axes objects, which are used to create individual plots.

Here's the general syntax:

main.py
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True)
98 chars
4 lines

nrows and ncols specify the number of rows and columns of subplots we want to create.

sharex and sharey are optional arguments that determine whether the subplots share the same x-axis and y-axis, respectively.

We can then use the individual Axes objects to plot our data. Here's an example:

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

# Generate some random data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Create the subplots
fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=False)

# Plot the data on each subplot
axes[0].plot(x, y1)
axes[1].plot(x, y2)

# Set some plot-level properties
fig.suptitle('Multiple Plots')
axes[0].set_ylabel('Sine')
axes[1].set_ylabel('Cosine')
axes[1].set_xlabel('X')

# Show the plot
plt.show()
477 chars
24 lines

This code generates two subplots, sharing the same x-axis, and plots the sine and cosine functions on them. We also set some plot-level properties such as a title and axis labels.

The resulting plot should display two stacked plots, with the sine function in the top plot and the cosine function in the bottom plot.

related categories

gistlibby LogSnag