【问题标题】:In matplotlib, how to add a table to a subplot without resizing other subplots在 matplotlib 中,如何在不调整其他子图大小的情况下将表格添加到子图
【发布时间】:2021-05-12 21:21:38
【问题描述】:

考虑这个例子:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(1, 3, figsize=(9,3), constrained_layout=False)
[ax.plot([[0,0],[1,1]]) for ax in axs]
fig.set_facecolor('silver')

table = axs[0].table(
    [[col + str(row) for col in 'ABC'] for row in range(3)],
    loc='top',
)

我想在子图的顶部(或底部)添加一个表格,并将这个特定的子图精确地减小表格的高度,这样表格就不会突出,图形不会放大并且所有子图具有相同的高度(包括表格)。我不想将表格放入绘图区域,即loc='upper center'

【问题讨论】:

    标签: python matplotlib layout


    【解决方案1】:

    想法是绘制图形,获取渲染的表格高度,然后将第一个轴缩小此高度(转换为图形坐标)。由于表格大小在轴坐标中,因此在降低轴高度时表格也会缩小。因此,我们必须将其在 y 方向上重新缩放相同的因子,以获得原始表格大小,并使顶部与其他轴整齐地对齐。

    import matplotlib.pyplot as plt
    
    fig, axs = plt.subplots(1, 3, figsize=(9,3), constrained_layout=False)
    [ax.plot([[0,0],[1,1]]) for ax in axs]
    fig.set_facecolor('silver')
    
    table = axs[0].table(
        [[col + str(row) for col in 'ABC'] for row in range(3)],
        loc='top',
    )
    
    table_box = fig.transFigure.inverted().transform_bbox(table.get_window_extent(fig.canvas.get_renderer()))
    ax_box = axs[0].get_position()
    axs[0].set_position([ax_box.x0, ax_box.y0, ax_box.width, (ax_box.height-table_box.height)])
    table.scale(1, ax_box.height/(ax_box.height-table_box.height))
    

    【讨论】:

    • 谢谢。我不喜欢解决方法。其实不用量表。我很乐意事先设置桌子的高度(比如轴坐标中的 0.3)。那么我们将如何进行呢?
    • @Mische:感谢您的解决方案中的 bbox 计算 (+1) 我想出了如何在不删除和重新添加表格的情况下做到这一点,请参阅更新的答案。
    【解决方案2】:

    最后我使用了一个常量table_height 设置用于表格的轴的分数。

    import matplotlib.pyplot as plt
    
    fig, axs = plt.subplots(1, 3, figsize=(9,3))
    [ax.plot([[0,0],[1,1]]) for ax in axs]
    fig.set_facecolor('silver')
    
    table_height = 0.3
    ax_box = axs[0].get_position()
    axs[0].set_position(
        [ax_box.x0, ax_box.y0, ax_box.width, ax_box.height * (1 - table_height)])
    
    table = axs[0].table(
        [[col + str(row) for col in 'ABC'] for row in range(3)],
        bbox=[0., 1., 1., table_height / (1 - table_height)]
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 2013-09-15
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      相关资源
      最近更新 更多