首页 > 解决方案 > matplotlib 在条形图标签下方绘制表格

问题描述

我正在使用以下代码在 matplotlib 中的条形图下方绘制一个表格。但是,我发现表格文本和条形图的 x 标签混合在一起。有没有办法将表格移到条形图的 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()
plt.xticks(rotation = 45)

plt.table(cellText=[code_size],
          rowLabels=['Code size'],
          loc='bottom')

plt.subplots_adjust(bottom=0.05)
plt.show()

标签: pythonmatplotlib

解决方案


使用子图来放置图形和表格是最容易的。我在这里参考一个很好的答案来回答这个问题。

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, ax_table) = plt.subplots(nrows=2, gridspec_kw=dict(height_ratios=[3,1]))

ax_table.axis('off')
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()
ax.tick_params(axis='x', labelrotation=45)

ax_table = plt.table(cellText=[code_size],
          rowLabels=['Code size'],
          loc='bottom')

plt.subplots_adjust(bottom=0.05)
plt.show()

在此处输入图像描述


推荐阅读