📜  Matplotlib-Subplot2grid()函数(1)

📅  最后修改于: 2023-12-03 15:17:35.639000             🧑  作者: Mango

Matplotlib-Subplot2grid() Function

subplot2grid() is a function in matplotlib library which allows the creation of a grid of subplots with custom sizes and arrangements. It is a useful tool for creating complex layouts of subplots within a single figure.

Syntax

The syntax of the subplot2grid() function is as follows:

ax = plt.subplot2grid(shape, loc, rowspan, colspan)

where

  • shape is a tuple defining the shape of the grid of subplots, e.g., (2, 3) means a grid with 2 rows and 3 columns
  • loc is a tuple defining the location of the subplot in the grid, e.g., (0, 1) means the subplot is located in the first row, second column
  • rowspan and colspan are integers defining the number of rows and columns the subplot will span, respectively.
Example
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)

# Creating grid of subplots with custom sizes and arrangements
fig = plt.figure(figsize=(8, 6))
ax1 = plt.subplot2grid((3, 3), (0, 0), rowspan=2, colspan=2)
ax2 = plt.subplot2grid((3, 3), (0, 2), rowspan=3)
ax3 = plt.subplot2grid((3, 3), (2, 0))
ax4 = plt.subplot2grid((3, 3), (2, 1), colspan=2)

# Plotting on the subplots
ax1.plot(x, y)
ax1.set_title('Sin(x^2)')
ax2.hist(y, bins=20)
ax2.set_title('Histogram')
ax3.scatter(x, y)
ax3.set_title('Scatter')
ax4.plot(y, x)
ax4.set_title('Y vs X')

plt.tight_layout()
plt.show()

In this example, we are creating a 3x3 grid of subplots with custom sizes and arrangements using the subplot2grid() function. We are then using the different subplots to plot a sine curve, a histogram, a scatter plot, and a line plot.

Conclusion

In conclusion, subplot2grid() is a useful function for creating complex layouts of subplots in a single figure. By specifying the shape of the grid, the location of the subplots, and the number of rows and columns they will span, it is possible to create a wide variety of layouts.