【问题标题】:Add a table to the right of two subplots在两个子图的右侧添加一个表格
【发布时间】:2020-09-06 16:22:51
【问题描述】:

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

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,但没有成功。感谢您的帮助!

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:

    我使用plt.subplot 提出了这个变通解决方案。垂直拉伸它的想法来自here,并从here 更改字体大小。您可以根据需要选择 y-scaling 值,即下面代码中的 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      相关资源
      最近更新 更多