Home >Backend Development >Python Tutorial >Can You Create AxesSubplot Objects Independently of Figures in Matplotlib?
Decoupling AxesSubplot Creation and Figure Addition
Problem:
Customizing matplotlib plots often requires the creation of AxesSubplot objects. However, these objects are typically bound to a Figure at their creation. This limits the ability to reuse AxesSubplots across multiple figures.
Question:
Is it possible to create AxesSubplot objects independently of Figure instances and then add them to different figures as needed?
Answer:
Yes, it is possible to decouple AxesSubplot creation and Figure addition in matplotlib. There are two main approaches:
Passing Functions with Axes Instances:
Appending Axes to Figures:
Example Code:
Passing Functions with Axes Instances:
import numpy as np import matplotlib.pyplot as plt def plot_sin(ax): x = np.linspace(0, 6 * np.pi, 100) ax.plot(x, np.sin(x)) ax.set_ylabel('Yabba dabba do!') fig1, (ax1, ax2) = plt.subplots(nrows=2) plot_sin(ax1) plot_sin(ax2) fig2 = plt.figure() ax3 = fig2.add_subplot(111) plot_sin(ax3) plt.show()
Appending Axes to Figures:
import numpy as np import matplotlib.pyplot as plt fig1 = plt.figure() ax1 = fig1.add_subplot(111) fig2 = plt.figure() ax2 = fig2.add_subplot(111) fig2.axes.append(ax1) plt.show()
The above is the detailed content of Can You Create AxesSubplot Objects Independently of Figures in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!