【问题标题】:Move center matplotlib table position when turning off axis关闭轴时移动中心matplotlib表位置
【发布时间】:2020-04-30 13:34:46
【问题描述】:

由于ax.axis('off'),下表不在中心位置。我想将表格左下角移动一点。我该怎么做?

  • 输出图片(白色矩形为result.png)

  • 代码
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import six

df = pd.DataFrame()
df['A'] = ['XXX_1', 'XXX_2', 'XXX_3', 'XXX_4',
           'XXX_5', 'XXX_6', 'XXX_7', 'XXX_8', 'XXX_9']
df['B'] = ['26,540', '1,072', '27,612', '2,975',
           '24,637', '20,000', '4,637', '(1,626)', '27,612']


def set_align_for_column(table, col, align="left"):
    cells = [key for key in table._cells if key[1] == col]
    for cell in cells:
        table._cells[cell]._loc = align


def render_mpl_table(data, col_width=3.0, row_height=0.4, font_size=12,
                     header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',
                     bbox=[0, 0, 1, 1], header_columns=0, **kwargs):

    size = (np.array(data.shape[::-1]) + np.array([0, 1])
            ) * np.array([col_width, row_height])

    fig, ax = plt.subplots(figsize=size)

    ax.axis('off')

    mpl_table = ax.table(cellText=data.values, bbox=bbox, cellLoc=['left', 'right'],
                         colLabels=data.columns, **kwargs)

    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)

    set_align_for_column(mpl_table, col=0, align="left")
    set_align_for_column(mpl_table, col=1, align="right")

    for k, cell in six.iteritems(mpl_table._cells):
        cell.set_edgecolor(edge_color)
        if k[0] == 0 or k[1] < header_columns:
            cell.set_text_props(weight='bold', color='w')
            cell.set_facecolor(header_color)
            cell._loc = 'center'
        else:
            cell.set_facecolor(row_colors[k[0] % len(row_colors)])

    return fig


fig = render_mpl_table(df, header_columns=0, col_width=2.0)
fig.suptitle('TITLE_ABC', fontsize=18, y=0.97)
fig.savefig('result.png', dpi=300)

更新 1

我使用@Yo_Chris 建议的方式再次创建

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    我认为您正在寻找设置为'tight'bbox_inches,然后是您希望图像周围的填充。我只是选择了 0.5 英寸作为示例。这是savefig documentation

    fig.savefig('result.png', dpi=300, bbox_inches='tight', pad_inches=.5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2014-06-02
      • 2021-10-19
      相关资源
      最近更新 更多