如何在Matplotlib表格的中间列添加折线图?
解决方法
要在Matplotlib表格的Chart列中添加对角线,核心是获取单元格的坐标边界,再在对应位置绘制线条。以下是两种常见需求的实现方式:
1. 为每个Chart单元格添加对角线
通过获取每个单元格的边界框(bbox),将其转换为坐标轴坐标后绘制对角线:
import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1, figsize=(16, 16)) ax.axis('off') nrows = 6 ncols = 3 table = ax.table(cellText=[['']*ncols]*nrows, loc='top', rowLoc='center', colLoc='center') # 设置表头 for j, text in zip(range(3), ['Group', 'Chart', 'Comments']): table[(0, j)].get_text().set_text(text) # 设置第一列内容 for i, text in zip(range(1, nrows), list('ABCDE')): table[(i, 0)].get_text().set_text(text) # 格式化单元格 for i in range(nrows): for j in range(ncols): table[(i, j)].set_height(0.2) table[(i, j)]._loc = 'center' table[(i, j)].set_fontsize(16) # 先绘制图表以计算单元格边界 fig.canvas.draw() # 为每个Chart列单元格添加对角线 for i in range(nrows): cell = table[(i, 1)] # 第二列(索引1)是Chart列 bbox = cell.get_bbox() # 将显示坐标转换为坐标轴坐标 x_left, y_bottom = ax.transAxes.inverted().transform((bbox.x0, bbox.y0)) x_right, y_top = ax.transAxes.inverted().transform((bbox.x1, bbox.y1)) # 绘制从左下角到右上角的对角线,可调整颜色、线宽 ax.plot([x_left, x_right], [y_bottom, y_top], color='black', linewidth=1.5) plt.show()
调整细节
- 若要绘制从左上角到右下角的对角线,将
plot的坐标改为[x_left, x_right], [y_top, y_bottom] - 若要让线条不紧贴单元格边框,可添加边距:
margin = 0.01 # 边距大小,按需调整 ax.plot([x_left + margin, x_right - margin], [y_bottom + margin, y_top - margin], color='black', linewidth=1.5)
2. 添加横跨整个Chart列的单条对角线
如果需要一条对角线贯穿整个Chart列的上下两端,可先计算整列的边界范围:
# (前面的表格创建代码同上) # 先绘制图表以计算单元格边界 fig.canvas.draw() # 获取Chart列所有单元格的边界范围 x_coords = [] y_coords = [] for i in range(nrows): cell = table[(i, 1)] bbox = cell.get_bbox() x_coords.extend([bbox.x0, bbox.x1]) y_coords.extend([bbox.y0, bbox.y1]) min_x = min(x_coords) max_x = max(x_coords) min_y = min(y_coords) max_y = max(y_coords) # 转换为坐标轴坐标 ax_x_start, ax_y_start = ax.transAxes.inverted().transform((min_x, min_y)) ax_x_end, ax_y_end = ax.transAxes.inverted().transform((max_x, max_y)) # 绘制横跨整列的对角线 ax.plot([ax_x_start, ax_x_end], [ax_y_start, ax_y_end], color='red', linewidth=3) plt.show()
关键说明:
- 必须调用
fig.canvas.draw()才能正确获取单元格的边界框,因为Matplotlib在渲染前不会计算这些坐标 - 使用
ax.transAxes.inverted().transform()将显示坐标(像素)转换为坐标轴的归一化坐标,确保线条位置准确
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

