【问题标题】:Saving matplotlib table creates a lot of whitespace保存 matplotlib 表会产生大量空白
【发布时间】:2017-03-23 22:00:58
【问题描述】:

我正在使用 matplotlib 和 python 2.7 创建一些表。当我保存表格时,即使表格只有 1 到 2 行,图像也会出现方形,当我稍后将它们添加到自动生成的 PDF 时会产生大量空白空间。 我如何使用代码的示例在这里...

import matplotlib.pyplot as plt

t_data = ((1,2), (3,4))
table = plt.table(cellText = t_data, colLabels = ('label 1', 'label 2'), loc='center')
plt.axis('off')
plt.grid('off')
plt.savefig('test.png')

这会产生这样的图像... You can see you can see the white space around it

奇怪地使用 plt.show() 在 GUI 中生成没有空格的表。

我尝试过使用各种形式的tight_layout=True 没有运气,以及使背景透明(它变得透明,但仍然存在)。

任何帮助将不胜感激。

【问题讨论】:

    标签: python matplotlib save plt


    【解决方案1】:

    由于表格是在轴内创建的,因此最终绘图大小将取决于轴的大小。因此,原则上一个解决方案可以是设置图形大小或先设置轴大小,然后让表格适应它。

    import matplotlib.pyplot as plt
    
    fig = plt.figure(figsize=(6,1))
    
    t_data = ((1,2), (3,4))
    table = plt.table(cellText = t_data, 
                      colLabels = ('label 1', 'label 2'),
                      rowLabels = ('row 1', 'row 2'),
                      loc='center')
    
    plt.axis('off')
    plt.grid('off')
    
    plt.savefig(__file__+'test2.png', bbox_inches="tight" )
    plt.show()
    

    另一种解决方案是让表格按原样绘制,并在保存之前找出表格的边界框。这允许创建一个围绕桌子非常紧凑的图像。

    import matplotlib.pyplot as plt
    import matplotlib.transforms
    
    t_data = ((1,2), (3,4))
    table = plt.table(cellText = t_data, 
                      colLabels = ('label 1', 'label 2'),
                      rowLabels = ('row 1', 'row 2'),
                      loc='center')
    
    plt.axis('off')
    plt.grid('off')
    
    #prepare for saving:
    # draw canvas once
    plt.gcf().canvas.draw()
    # get bounding box of table
    points = table.get_window_extent(plt.gcf()._cachedRenderer).get_points()
    # add 10 pixel spacing
    points[0,:] -= 10; points[1,:] += 10
    # get new bounding box in inches
    nbbox = matplotlib.transforms.Bbox.from_extents(points/plt.gcf().dpi)
    # save and clip by new bounding box
    plt.savefig(__file__+'test.png', bbox_inches=nbbox, )
    
    plt.show()
    

    【讨论】:

    • 第二种方法效果很好!感谢您的帮助,这是一个巨大的修复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多