Matplotlib表格布局问题

2024-04-25 06:48:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把一张大桌子放进一份A4的报告里。pyplot.show文件()显示布局,使整个表可见。然而,pyplot.savefig文件()生成一个pdf文件,其中表被图形隐藏。(example of pdf concealing the table)我想让pdf显示整个表,而不是隐藏它。请参阅下面的代码以获取问题的摘要。你知道吗

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.widgets import TextBox


def BadTable(savefile: str):
    fig = plt.figure(constrained_layout=True, figsize=(8.27, 11.69)) #A4 size                                                                                                                                      
    fig.suptitle('Title')

    gs = GridSpec(3, 1, figure=fig)
    ax_desc = fig.add_subplot(gs[0, :])
    ax_table = fig.add_subplot(gs[1, :])
    ax_graph = fig.add_subplot(gs[2, :])

    #Description box                                                                                                                                                                                               
    TextBox(ax_desc, '', initial='Hello world')

    #Table                                                                                                                                                                                                         
    ax_table.tick_params(labelbottom=False, labelleft=False)

    nums = np.random.randint(0, 10, (30,10))
    ax_table.table(cellText=nums, colLabels=range(10), loc='center')
    ax_table.axis('off')
    ax_table.axis('tight')

    ax_graph.plot(range(20), range(20))

    if savefile is None:
        plt.show()
    elif type(savefile) is str:
        plt.savefig(savefile)
    else:
        raise Exception()

#Table fits                                                                                                                                                                                                        
BadTable(None)

#Table does not fit                                                                                                                                                                                                
BadTable('badpdf.pdf')

Tags: 文件importgsaddpdfmatplotlibtablefig
2条回答

首先我想说的是,产生最佳效果的行为不一定是“正确的”。因此,我通常建议坚持使用@Patol's answer中的解决方案,它在理论上也给出了“正确”的行为。你知道吗

在这个问题上,约束布局和表格单元高度优化之间存在着相互影响的关系。你知道吗

要了解这一点,让我们关闭constrained_layout。(同时将绘图设为半transparent以查看表与绘图重叠,并为其提供背景色以查看其范围。)

然后比较constrained_layout=True(右边)

import numpy as np import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from matplotlib.widgets import TextBox def BadTable(savefile: str): fig = plt.figure(constrained_layout=False, figsize=(8.27, 11.69)) #A4 size fig.suptitle('Title') gs = GridSpec(3, 1, figure=fig) ax_desc = fig.add_subplot(gs[0, :]) ax_table = fig.add_subplot(gs[1, :]) ax_graph = fig.add_subplot(gs[2, :]) #Description box TextBox(ax_desc, '', initial='Hello world') #Table ax_table.tick_params(labelbottom=False, labelleft=False) nums = np.random.randint(0, 10, (30,10)) ax_table.table(cellText=nums, colLabels=range(10), loc='center') ax_table.axis('off') ax_graph.patch.set_alpha(0.7) ax_graph.plot(range(20), range(20)) if savefile is None: plt.show() elif type(savefile) is str: plt.savefig(savefile) else: raise Exception() #Table does not fit BadTable('badpdf.png') plt.show()

现在,基于表的原始扩展,约束布局为图中的元素分配了空间。有桌子的轴有了更大的空间。 但是,表现在有了更多的空间,它会自行扩展,因为它认为自己可以使用这些空间。这导致它再次重叠。你知道吗

你能做的就是重申这一点。给定额外的空间,让受限的布局再次优化空间,通过再次绘制图形

fig.canvas.draw()

现在,额外的空间量将小于第一步中的空间量。因此,表将不再增长,而是重新分配给它的空间。(左)

再重复一次,即添加第二个对fig.canvas.draw()的调用,最终会让竞争条件收敛。(右)

因此,一个可能的解决方案是在再次绘制以进行最终保存之前至少调用draw()两次

fig.canvas.draw()
fig.canvas.draw()
fig.savefig(savefile)

鉴于上述情况,我们现在可以回答一个问题:为什么plt.show()显示了看似正确的数字?
因为在GUI窗口中显示比屏幕大的图形会导致图形需要调整大小。每个调整大小的步骤都需要重新绘制图形。所以基本上你会得到至少一个额外的绘制步骤,我们已经在上面看到,这样额外的绘制步骤会有调整桌子高度的效果,这样就不会发生重叠。你知道吗

你会为GridSpec寻找height_ratios关键字吗?你知道吗

gs = GridSpec(3, 1, figure=fig, height_ratios=[1, 10, 4])产生

enter image description here

Here也是一个很好的指南。你知道吗

相关问题 更多 >