import matplotlib.pyplot as plt # create a figure with 2 subplots fig = plt.figure() ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) # plot some data on each subplot ax1.plot([1,2,3],[4,5,6]) ax2.scatter([1,2,3],[4,5,6]) plt.show()
import numpy as np import matplotlib.pyplot as plt # create some sample data x = np.linspace(0, 2*np.pi, 100) y1 = np.sin(x) y2 = np.cos(x) # create a figure with 1 row and 2 columns fig, axs = plt.subplots(1, 2) # plot each data set on its own subplot axs[0].plot(x, y1) axs[1].plot(x, y2) plt.show()In this example, two subplots are created side by side, each plotting a different mathematical function (sine and cosine). The add_subplot method is not explicitly used in this example, but is called implicitly by the plt.subplots method. Overall, the use of add_subplot is an important tool for creating complex figures with multiple subplots. It allows for easy organization and placement of plot elements within a single figure.