Matplotlib柱状图下方绘制表格与X轴标签重叠如何下移表格
解决方案
解决这个重叠问题只需要两处核心调整:一是给画布底部预留足够的空白区域,二是手动调整表格的垂直位置,将其移到X轴标签下方即可,修改后的完整代码如下:
import numpy as np import matplotlib.pyplot as plt labels = ['a', 'longlonglong', 'bbb', 'ccc', 'dddddddd', 'eeeee', 'ffff', 'ggggggggg'] code_size = ['5KB', '83KB', '1.7MB', '18KB', '1MB', '18KB', '4MB', '55KB'] step1 = [0.75, 1.22, 20.27, 0.49, 5.52, 11.76, 2.30, 0.64] step2 = [0.89, 3.62, 18.69, 0.22, 9.61, 14.06, 1.28, 0.27] width = 0.8 fig, ax = plt.subplots() ax.bar(labels, step1, width, label='Step 1') ax.bar(labels, step2, width, bottom=step1, label='Step 2') ax.set_ylabel('Time used (s)') ax.set_title('Time and size') ax.legend() # 增加ha='right'让旋转后的标签右对齐,显示更整齐 plt.xticks(rotation = 45, ha='right') # 接收table返回值,后续调整位置 table = plt.table(cellText=[code_size], rowLabels=['Code size'], loc='bottom') # 手动设置表格位置:[左边界, 下边界, 宽度, 高度],下边界设为负即可下移表格 table.set_bbox([0, -0.3, 1, 0.1]) # 增大底部留白比例,给标签和表格留足空间 plt.subplots_adjust(bottom=0.25) plt.show()
关键参数说明
plt.subplots_adjust(bottom=0.25):调整画布底部的留白占比,数值越大底部留白越多,你可以根据标签长度、表格大小自行调整这个数值。table.set_bbox([0, -0.3, 1, 0.1]):完全自定义表格的位置和尺寸,下边界参数设为负数就会将表格移动到坐标轴区域的下方,数值越小(越负)表格位置越靠下。plt.xticks的ha='right':让旋转45度后的标签右对齐,避免标签和柱体位置错位。
内容的提问来源于stack exchange,提问作者xiaogw
相关产品推荐
相关产品推荐

