代码之家  ›  专栏  ›  技术社区  ›  Marc Maxmeister

使用后端PDF PdfPages保存matplotib表格时,无法将表格居中放置在PDF页面上

  •  0
  • Marc Maxmeister  · 技术社区  · 6 年前

    我可以在jupyter笔记本中生成matplotlib表(没有任何明显关联的绘图),但当我尝试使用matplotlib的内部 backend_pdf.PdfPages 包装器,它永远不会出现在页面的中心。

    'top' , 'center' 'bottom' ,以及偏移量和 savefig(pad_inches)

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    
    col_names = ["this", "that","the other","4","5","6"]
    page_data = np.random.randint(100, size=(40,6))
    
    # stringify numbers: tables can't have ints in them.
    for idx, sub in enumerate(page_data):
        page_data[idx] = [str(i) for i in sub]
    
    fig, axs = plt.subplots(1, figsize=(10,8))
    axs.axis('off')
    _table = plt.table(
        cellText=page_data,
        colLabels=col_names,
        loc='top',
        edges='open',
        colLoc='right')
    
    # and now, the PDF doesn't fit on page    
    pdf = PdfPages('test.pdf')
    pdf.savefig(fig)
    pdf.close()
    

    我的直觉是,仍然有一个看不见的人物占据了空间,这将推高我页面上的所有内容。我如何删除该数字,或将其大小调整为零,并且只使用PDF格式保存表格文本?

    PDF输出截图: enter image description here

    enter image description here

    0 回复  |  直到 6 年前
        1
  •  1
  •   William Miller devops-admin    6 年前

    使用 loc='center'

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    
    col_names = ["this", "that","the other","4","5","6"]
    data = np.random.randint(100, size=(40,6)).astype('str')
    
    fig, ax = plt.subplots(1, figsize=(10,10))
    ax.axis('off')
    _table = plt.table(cellText=data, colLabels=col_names, 
                       loc='center', edges='open', colLoc='right')
    
    pdf = PdfPages('test.pdf')
    pdf.savefig(fig)
    pdf.close()
    

    enter image description here

    Axes 例子使用这种方法可能更安全 matplotlib.axes.Axes.table 使用。


    笔记 我在Matplotlib 2.2.5和3.2.1中测试过,如果上面的代码确实产生了我所展示的结果,请考虑更新您的MaMattLIB安装。