Plot multiple plots in Matplotlib

Plot multiple plots in Matplotlib

In matplotlib, you can create multiple plots in a single figure using the subplot() function. The subplot() function allows you to arrange plots in a grid format.

Here's a guide on how to plot multiple plots using matplotlib:

1. Import the necessary libraries:

import matplotlib.pyplot as plt import numpy as np 

2. Use subplot() to create multiple plots:

The subplot() function takes three arguments: the number of rows, the number of columns, and the index of the current plot.

For example, if you want to create 2x2 plots (2 rows and 2 columns), you'll use:

x = np.linspace(0, 10, 100) plt.figure(figsize=(10, 6)) # Optional: Set figure size # First subplot plt.subplot(2, 2, 1) plt.plot(x, np.sin(x)) plt.title('Sin(x)') # Second subplot plt.subplot(2, 2, 2) plt.plot(x, np.cos(x)) plt.title('Cos(x)') # Third subplot plt.subplot(2, 2, 3) plt.plot(x, np.tan(x)) plt.title('Tan(x)') plt.ylim(-10, 10) # Limit y-axis for tan(x) since it approaches infinity at certain points. # Fourth subplot plt.subplot(2, 2, 4) plt.plot(x, -np.sin(x)) plt.title('-Sin(x)') plt.tight_layout() # Adjusts the spaces between plots for better layout plt.show() 

In the above code:

  • plt.subplot(2, 2, 1) selects the first plot in a 2x2 grid.
  • plt.subplot(2, 2, 2) selects the second plot, and so on.

3. Adjusting the space:

Sometimes, when you plot multiple subplots, the axis labels or titles might overlap. You can use plt.tight_layout() to automatically adjust and add padding between subplots for better clarity.

You can also use plt.subplots_adjust() for more manual control over the spacing.

Using plt.subplots():

Another way to create multiple plots is using plt.subplots(), which returns a figure and an array of axes objects:

fig, axes = plt.subplots(2, 2, figsize=(10, 6)) axes[0, 0].plot(x, np.sin(x)) axes[0, 0].set_title('Sin(x)') axes[0, 1].plot(x, np.cos(x)) axes[0, 1].set_title('Cos(x)') axes[1, 0].plot(x, np.tan(x)) axes[1, 0].set_title('Tan(x)') axes[1, 0].set_ylim(-10, 10) axes[1, 1].plot(x, -np.sin(x)) axes[1, 1].set_title('-Sin(x)') plt.tight_layout() plt.show() 

In this approach, you can directly use the axes object to plot, which can be more intuitive when dealing with multiple subplots.


More Tags

angular2-material picker widget set controllers autoconf include strcat fullcalendar-4 routeparams

More Programming Guides

Other Guides

More Programming Examples