matplotlib 如何使用Gridspec创建子图

ar5n3qh5  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(111)

如何生成3x3子图,其中第一列和第二列填充轮廓,第三列将在每行中有两个堆叠的水平线图?
这就是我想要的布局(不按比例)。任何通用答案都是好的(https://i.stack.imgur.com/D58zL.png
下面的代码是一个例子,但我希望第三列中的线图在不同的面板中,而不是在一个重叠图中。

import numpy as np
 import matplotlib.pyplot as plt

 # Generate some random data for the contour plots
 x = np.linspace(-5, 5, 100)
 y = np.linspace(-5, 5, 100)
 X, Y = np.meshgrid(x, y)
 Z1 = np.exp(-(X ** 2 + Y ** 2) / 10)
 Z2 = np.exp(-((X - 1) ** 2 + (Y - 1) ** 2) / 10)

 # Create the figure and subplots
 fig, axes = plt.subplots(3, 3, figsize=(12, 9))

 # Plot filled contour in the first column
 axes[0, 0].contourf(X, Y, Z1)
 axes[1, 0].contourf(X, Y, Z2)
 axes[2, 0].contourf(X, Y, Z1 + Z2)

 # Plot filled contour in the second column
 axes[0, 1].contourf(X, Y, Z1)
 axes[1, 1].contourf(X, Y, Z2)
 axes[2, 1].contourf(X, Y, Z1 + Z2)

 # Generate some random data for the line plots
 x = np.linspace(0, 2 * np.pi, 100)
 y1 = np.sin(x)
 y2 = np.cos(x)
 y3 = np.tan(x)
 y4 = np.exp(-x)
 y5 = np.sqrt(x)
 y6 = x ** 2

 # Plot stacked line plots in the third column
 axes[0, 2].plot(x, y1)
 axes[1, 2].plot(x, y2)
 axes[2, 2].plot(x, y3)
 axes[0, 2].plot(x, y4)
 axes[1, 2].plot(x, y5)
 axes[2, 2].plot(x, y6)

 # Set titles and labels for subplots
 axes[0, 0].set_title('Contour 1')
 axes[0, 1].set_title('Contour 2')
 axes[0, 2].set_title('Line Plots')

 # Adjust the spacing between subplots
 plt.subplots_adjust(hspace=0.3, wspace=0.3)

 # Show the plot
 plt.show()

字符串
线图和等高线图的比例尺应相同。

5tmbdcev

5tmbdcev1#

您可以使用make_axes_locatable,然后使用append_axes附加轴。
绘制直线的代码:

from mpl_toolkits.axes_grid1 import make_axes_locatable
# Plot stacked line plots in the third column

axes[0, 2].plot(x, y1)
divider_0 = make_axes_locatable(axes[0, 2])
cax0 = divider_0.append_axes("bottom", size="100%", pad=0.25, sharex=axes[0, 2])
cax0.plot(x, y4)

axes[1, 2].plot(x, y2)
divider_1 = make_axes_locatable(axes[1, 2])
cax1 = divider_1.append_axes("bottom", size="100%", pad=0.25, sharex=axes[1, 2])
cax1.plot(x, y5)

axes[2, 2].plot(x, y3)
divider_2 = make_axes_locatable(axes[2, 2])
cax2 = divider_2.append_axes("bottom", size="100%", pad=0.25, sharex=axes[2, 2])
cax2.plot(x, y6)

字符串
图的输出:


的数据

更新

如果要更改列的相对宽度,可以在图形初始化期间使用参数width_ratios

fig, axes = plt.subplots(3, 3, figsize=(12, 9), width_ratios=[1, 1, 2])


新输出:


相关问题