You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调整Matplotlib表格单元格尺寸后,如何实现文本居中?

解决Matplotlib表格宽高比悬殊时文本无法居中的问题

问题根源

  • 多次调用cell.set_text_props()会覆盖之前设置的属性:后续设置字体属性的操作会冲掉之前的对齐方式配置。
  • table.scale()与手动设置单元格尺寸冲突,干扰了Matplotlib的布局计算逻辑,导致对齐失效。

修复后的完整代码

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import pandas as pd

class SummaryTable:
    def __init__(self, df):
        self.df = df

    def create_table(self):
        # 调整画布尺寸适配宽型表格
        fig, ax = plt.subplots(figsize=(10, 3))
        ax.axis('off')

        # 提取数据
        catchment_id = self.df['CatchmentId'].values[0]
        catchment_name = self.df['CatchmentName'].values[0]
        mode = self.df['Mode'].values[0]
        minutes = self.df['Minutes'].values[0]

        table_data = [
            ['Location', catchment_id],
            [catchment_name, f'{minutes} minutes by {mode}']
        ]

        # 创建表格时明确指定cellLoc='center'
        table = ax.table(cellText=table_data, loc='center', cellLoc='center',
                         cellColours=[['#94c11f', '#94c11f'],
                                      ['#94c11f', '#94c11f']],
                         edges='closed')

        # 基础样式配置
        table.auto_set_font_size(False)
        table.set_fontsize(14)
        font_properties_header = FontProperties(weight='bold')
        font_properties_normal = FontProperties()

        # 遍历单元格统一设置样式,避免属性覆盖
        for (row, col), cell in table.get_celld().items():
            cell.set_facecolor('#94c11f')
            cell.set_linewidth(0.5)
            cell.set_edgecolor('white')
            cell.set_height(0.3)
            cell.set_width(0.5)  # 两列各占一半宽度,适配画布

            # 一次性传入所有文本属性,包含对齐方式和字体配置
            text_props = {
                'color': 'white',
                'horizontalalignment': 'center',
                'verticalalignment': 'center'
            }
            if row == 0:
                text_props['fontproperties'] = font_properties_header
            else:
                text_props['fontproperties'] = font_properties_normal
            
            cell.set_text_props(**text_props)

        return fig

# 测试示例
if __name__ == '__main__':
    test_df = pd.DataFrame({
        'CatchmentId': ['C001'],
        'CatchmentName': ['Riverdale Catchment'],
        'Mode': ['car'],
        'Minutes': [25]
    })
    table_obj = SummaryTable(test_df)
    fig = table_obj.create_table()
    plt.show()

核心修复点

  • 合并文本属性设置:将对齐方式、颜色、字体配置一次性传入set_text_props(),避免后续调用覆盖对齐属性。
  • 移除table.scale():手动设置单元格宽高时,缩放方法会干扰布局计算,导致对齐逻辑异常。
  • 适配画布尺寸:通过figsize设置宽画布,匹配“信箱形”单元格的宽高比需求。
  • 统一列宽分配:两列各设置为0.5的宽度,确保总宽度适配画布范围,避免布局偏移。

内容的提问来源于stack exchange,提问作者David Graham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 16:14:58