如何绘制带自动换行文本的Matplotlib表格?
解决Matplotlib表格长文本自动换行问题
Matplotlib自带的表格组件默认不会对超长文本自动换行,要实现这个效果,需要手动根据单元格宽度拆分文本为多行,再传入表格渲染。以下是修改后的完整代码:
import pandas as pd import matplotlib.pyplot as plt def wrap_text(text, renderer, fontsize, max_width): """根据单元格宽度拆分文本为多行,避免截断单词""" wrapped_lines = [] words = text.split() current_line = '' for word in words: test_line = current_line + (word if not current_line else ' ' + word) # 计算当前文本的实际显示宽度 text_width = renderer.get_text_width_height(test_line, fontsize=fontsize)[0] if text_width <= max_width: current_line = test_line else: if current_line: wrapped_lines.append(current_line) current_line = word if current_line: wrapped_lines.append(current_line) return '\n'.join(wrapped_lines) # 原始数据 dati = { 'Testo 1': ['Primo testo breve', 'Altro testo breve', 'Un altro breve testo'], 'Testo 2': ['Testo lungo che può contenere molte parole...', 'Questo è un altro testo lungo con molte parole e frasi.', 'Ancora un esempio di testo lungo.'], 'Testo 3': ['Testo molto lungo che supera la riga precedente e contiene un gran numero di parole e frasi. Questo testo dovrebbe essere sufficientemente lungo per dimostrare il funzionamento del DataFrame.', 'Questa è unaltra riga di esempio per il testo lungo.', 'Una terza riga per il testo lungo.'] } df = pd.DataFrame(dati) # 创建画布和轴 fig = plt.figure(figsize=(8, 6)) ax1 = fig.add_subplot(111) ax1.axis('off') # 先创建临时表格获取列宽 temp_table = ax1.table(cellText=df.values, colLabels=df.columns, cellLoc='left', loc='center', bbox=[0, 0, 1, 1]) temp_table.auto_set_font_size(False) temp_table.set_fontsize(8) # 获取渲染器和各列实际宽度 renderer = fig.canvas.get_renderer() fontsize = 8 col_widths = [] for col in range(len(df.columns)): cell = temp_table[(0, col)] # 转换为实际像素宽度 col_width = cell.get_width() * fig.dpi * fig.get_figwidth() col_widths.append(col_width) # 处理所有单元格文本,添加换行 wrapped_data = [] for row in df.values: wrapped_row = [] for idx, text in enumerate(row): wrapped_text = wrap_text(text, renderer, fontsize, col_widths[idx]) wrapped_row.append(wrapped_text) wrapped_data.append(wrapped_row) # 替换为最终表格 ax1.clear() ax1.axis('off') final_table = ax1.table(cellText=wrapped_data, colLabels=df.columns, cellLoc='left', loc='center', bbox=[0, 0, 1, 1]) final_table.auto_set_font_size(False) final_table.set_fontsize(8) # 自动调整行高适配多行文本 final_table.auto_set_column_width(col=list(range(len(df.columns)))) plt.tight_layout() plt.show()
关键说明
- 文本拆分逻辑:按单词拆分长文本,通过Matplotlib渲染器计算实际显示宽度,确保每行文本不超出单元格边界,避免生硬截断单词。
- 临时表格的作用:先创建临时表格获取各列的实际宽度,以此为依据拆分文本,保证换行逻辑和实际表格布局匹配。
- 行高自动适配:通过
auto_set_column_width和tight_layout让表格行高自动适应多行文本,避免内容被遮挡。
内容的提问来源于stack exchange,提问作者Gaetano
相关产品推荐
相关产品推荐

