在两个子图的右边添加一个 table

Add a table to the right of two subplots

我想使用 matplotlib 在两个子图的右侧添加一个 table。我尝试了以下代码,但它只将 table 与一个子图对齐...

import matplotlib.pyplot as plt
import numpy as np

t = np.linspace(-1,1,100)

fig, axs = plt.subplots(2, 1, constrained_layout=True)
ax1, ax2 = axs

ax1.plot(t, t**2)
ax1.set_title('One plot')
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')
ax1.legend()

ax2.plot(t, t**3)
ax2.set_title('Another plot')
ax2.set_xlabel('Time')
ax2.set_ylabel('Amplitude')

clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
the_table = plt.table(cellText=clust_data,
                      colLabels=collabel,
                      loc='right')

我也尝试过使用 Gridspec 但没有成功。感谢您的帮助!

我使用 plt.subplot 想出了这个解决方案。垂直拉伸的想法来自 and to change the fontsize from here。您可以根据需要选择y轴缩放值,在下面的代码中为1.65。

ax1 = plt.subplot(221)
ax1.plot(t, t**2)
ax1.set_title('One plot')
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')

ax2 = plt.subplot(223)
ax2.plot(t, t**3)
ax2.set_title('Another plot')
ax2.set_xlabel('Time')
ax2.set_ylabel('Amplitude')

ax3 = plt.subplot(122)
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
the_table = ax3.table(cellText=clust_data,
                      colLabels=collabel,
                      loc='center')
the_table.scale(1,1.65)
the_table.auto_set_font_size(False)
the_table.set_fontsize(4)
ax3.axis('off')
plt.tight_layout()