matplotlib - Matplotlib 表格大小和位置
问题描述
我正在尝试制作一个尺寸为 Nx7 的表格,其中 N 是一个变量。
通过 matplotlib 制作合适大小的表格非常具有挑战性。
我想把它放在情节的中心,标题就在桌子的正上方。
这是我的代码
data = [
['A', 'B', 'C', 'D', 'E', 'F'],
['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
['100%', '200%', 'O', 'X', '1.2%', '100', '200'],
['100%', '200%', 'O', 'X', '1.2%', '100', '200']]
fig, ax1 = plt.subplots(dpi=200)
column_headers = data.pop(0)
row_headers = [x.pop(0) for x in data]
rcolors = np.full(len(row_headers), 'linen')
ccolors = np.full(len(column_headers), 'lavender')
cell_text = []
for row in data:
cell_text.append([x for x in row])
table = ax1.table(cellText=cell_text,
cellLoc='center',
rowLabels=row_headers,
rowColours=rcolors,
rowLoc='center',
colColours=ccolors,
colLabels=column_headers,
loc='center')
fig.tight_layout()
table.scale(1, 0.5)
table.set_fontsize(16)
# Hide axes
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)
# Add title
ax1.set_title('{}\n({})'.format(title, subtitle), weight='bold', size=14, color='k')
fig.tight_layout()
plt.savefig(filename)
在我的代码中,有几个问题。
- 标题重叠在桌子上。
- 整个数字不知何故从中心向右移动。(结果图像的左侧被空白区域填充)
- 表格中文字的大小不是16。(比标题小很多)
谢谢你。
解决方案
这是一些绘制表格的代码。
一些评论:
- 在 matplotlib 中的支持
table
是相当基本的。它主要用于在现有绘图上以表格形式添加一些文本。 - 使用
.pop()
使代码难以推理。在 Python 中,通常从给定列表开始创建新列表。 - 由于绘图的足够大小高度取决于行数,因此可以将其计算为某个倍数。确切的值取决于完整的表格,尝试一下是有意义的。下面的值似乎适用于给定的示例数据。
dpi
和tight
边界框可以设置为参数savefig()
。- 不同的 matplotlib 版本的行为可能略有不同。下面的代码是用 matplotlib 3.3.3 测试的。
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = [['A', 'B', 'C', 'D', 'E', 'F']] + [['100%', '200%', 'O', 'X', '1.2%', '100', '200']] * N
column_headers = data[0]
row_headers = [row[0] for row in data[1:]]
cell_text = [row[1:] for row in data[1:]]
fig, ax1 = plt.subplots(figsize=(10, 2 + N / 2.5))
rcolors = np.full(len(row_headers), 'linen')
ccolors = np.full(len(column_headers), 'lavender')
table = ax1.table(cellText=cell_text,
cellLoc='center',
rowLabels=row_headers,
rowColours=rcolors,
rowLoc='center',
colColours=ccolors,
colLabels=column_headers,
loc='center')
table.scale(1, 2)
table.set_fontsize(16)
ax1.axis('off')
title = "demo title"
subtitle = "demo subtitle"
ax1.set_title(f'{title}\n({subtitle})', weight='bold', size=14, color='k')
plt.savefig("demo_table.png", dpi=200, bbox_inches='tight')
推荐阅读
- r - 当函数来自不同的脚本时,正则表达式在 R 中的工作方式不同
- python-3.x - 在 wxpython 中形成一个 Ultimatelistctrl
- python - 如何使用matplotlib在Python中沿圆的圆周移动多个点?
- php - 如何使用 PHP 计算特定页面上的真实访问者数量
- excel - 是否立即声明了电子表格中所有模块中的所有全局变量?
- react-native - React Native“无法打开设置重新映射的类缓存”
- c++ - for循环中的计数器在执行后错误地递增
- android - 更新 gradle ver apk 大小两倍后,为什么?
- python - 字符串格式化和传递
- python - 使用openpyxl更改excel列格式类型