python - 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()
解决方案
使用子图来放置图形和表格是最容易的。我在这里参考一个很好的答案来回答这个问题。
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()
推荐阅读
- scala - 映射列表时使用归纳结构的Scala案例匹配失败
- javascript - 在 React 中使用 axios 下载单个文件为 pdf 和多个文件为 zip
- python - 为 pandas 中的每个类按平均值查找具有代表性的观察值
- api - 使用 curl 发布“使用错误/非法格式或缺少 URL”
- python - 如何在networkx图中显示连接列表?
- mysql - 如何添加一个mysql列值作为where查询条件的关键字?
- mysql - 如何在 SQL 中正确插入 CSV 文件?
- reactjs - 如何从 React Native 中的子组件访问父级中的多个状态
- autodesk-forge - Forge Autodesk:标记拖动事件触发器
- flutter - 调整窗口大小时如何设置新状态?