如何用Matplotlib/Pandas在子图中绘制DataFrame为表格?
在Matplotlib子图中渲染STDF测试数据的DataFrame表格
嘿,我刚好在处理STDF数据可视化的时候踩过类似的坑!要在Matplotlib的子图(121布局里的第一个子图)里渲染10列、几十行的DataFrame表格,table()方法确实是核心,但直接用很容易出现文字拥挤、显示不全的问题,我给你整理了一套实用的解决方案,附完整代码:
完整示例代码
import pandas as pd import matplotlib.pyplot as plt # 模拟STDF格式的ATE测试数据(10列,30行) test_data = { "Test_ID": [f"T{i:03d}" for i in range(1, 31)], "Test_Name": [f"Param_{i}" for i in range(1, 31)], "Meas_Value": [round(5.0 + 1.2 * pd.np.random.randn(), 3) for _ in range(30)], "Spec_Lower": [3.5] * 30, "Spec_Upper": [6.5] * 30, "Pass_Fail": ["Pass" if 3.5 < x < 6.5 else "Fail" for x in [round(5.0 + 1.2 * pd.np.random.randn(), 3) for _ in range(30)]], "Test_Site": [1] * 15 + [2] * 15, "Wafer_ID": ["WF-2024-007"] * 30, "Die_Coord_X": [pd.np.random.randint(1, 25) for _ in range(30)], "Die_Coord_Y": [pd.np.random.randint(1, 25) for _ in range(30)] } df_test = pd.DataFrame(test_data) # 创建1行2列的子图布局,第一个子图放表格,第二个可用于绘制测试结果图表 fig, (ax_table, ax_chart) = plt.subplots(1, 2, figsize=(18, 9)) # 隐藏表格子图的坐标轴,避免多余线条干扰 ax_table.axis('off') # 裁剪数据:保留前15行(几十行全显示会过度拥挤,按需调整) df_trimmed = df_test.head(15) # 在子图中添加表格 test_table = ax_table.table( cellText=df_trimmed.values, colLabels=df_trimmed.columns, loc='center', cellLoc='center', fontsize=10, colWidths=[0.1] * 10 # 10列平均分配宽度,适配子图 ) # 美化表格:给表头设置深色背景+白色文字,提升可读性 for (row, col), cell in test_table.get_celld().items(): if row == 0: # 表头行 cell.set_facecolor('#2c3e50') cell.set_text_props(color='white', weight='bold') # 第二个子图示例:绘制测试值的直方图 ax_chart.hist(df_test['Meas_Value'], bins=12, edgecolor='black', alpha=0.7) ax_chart.axvline(x=3.5, color='red', linestyle='--', label='Spec Lower') ax_chart.axvline(x=6.5, color='red', linestyle='--', label='Spec Upper') ax_chart.set_title('ATE Test Value Distribution') ax_chart.set_xlabel('Measured Value') ax_chart.set_ylabel('Test Count') ax_chart.legend() # 自动调整布局,避免元素重叠 plt.tight_layout() plt.show()
关键优化点说明
- 隐藏坐标轴:用
ax_table.axis('off')去掉表格子图的坐标轴,让表格显示更干净。 - 数据裁剪:几十行全塞进子图会导致文字挤成一团,用
head(n)或筛选关键行来控制显示行数。 - 列宽适配:通过
colWidths参数给10列平均分配宽度,确保每列内容不溢出。 - 字体与样式:调小
fontsize避免文字溢出,给表头加样式区分,提升表格可读性。 - 布局调整:用
figsize设置合适的画布尺寸,配合plt.tight_layout()避免子图间元素重叠。
如果需要显示更多行,可以把布局改成2行1列(表格在上,图表在下),并增大画布的高度(比如figsize=(12, 15)),这样表格有足够空间展示更多内容。
内容的提问来源于stack exchange,提问作者McNibbler
相关产品推荐
相关产品推荐

