Python Matplotlib 如何仅获取表格

Ari*_*ian 4 python matplotlib

我修改了示例代码并使表格按照我想要的方式工作,但是,仍然有一个框,图表将位于表格下方。我想摆脱那个盒子。请注意,该表有 5 行(包括列标签)和 8 列(包括行标签)。

相关代码:

columns = ('Last', 'High', 'Low', 'Chg.', 'Chg. %', 'Time', 'T?')
rows = ['Gold', 'Silver', 'Copper', 'Aluminum']
scatter_x = (1, 2, 3)
scatter_y = (1224.53, 1231.76, 1228.70)
fig = plt.figure(1)
gridspec.GridSpec(4,3)

#Table - Main table
plt.subplot2grid((4,3), (0,0), colspan=2, rowspan=2)
plt.table(cellText=data_list,
          rowLabels=rows,
          colLabels=columns,
          loc='top')
plt.subplots_adjust(left=0.2,top=0.8)
plt.yticks([])
plt.xticks([])

#Gold Scatter - Small scatter to the right
plt.subplot2grid((4,3), (0,2))
plt.scatter(scatter_x, scatter_y)
plt.ylabel('Gold Last')


fig.tight_layout()
fig.set_size_inches(w=6, h=5)
fig_name = 'plot.png'
fig.savefig(fig_name)
plt.show()
Run Code Online (Sandbox Code Playgroud)

它产生了这个: 查看表格下方的空方块

一个问题:我如何将填充设置在桌子上,使其不会在顶部和左侧被切断?

Imp*_*est 5

可以在轴内或轴外的不同位置添加该表。这是由loc论证决定的。在这种情况下,您似乎不想将表格放在轴外,而是放在里面。因此,不要使用"top", "bottom", "left", 中的任何一个,"right"而是使用例如 loc="upper center"

然后,您可以通过ax.axis("off"). 为了不让行标题被图形边距裁剪,您可以决定不使用tight layout.

完整示例:

import matplotlib.pyplot as plt
import numpy as np

columns = ('Last', 'High', 'Low', 'Chg.', 'Chg. %', 'Time', 'T?')
rows = ['Gold', 'Silver', 'Copper', 'Aluminum']

data_list = np.random.randint(10,90, size=(len(rows), len(columns)))
scatter_x = (1, 2, 3)
scatter_y = (1224.53, 1231.76, 1228.70)

fig = plt.figure(1)
fig.subplots_adjust(left=0.2,top=0.8, wspace=1)

#Table - Main table
ax = plt.subplot2grid((4,3), (0,0), colspan=2, rowspan=2)
ax.table(cellText=data_list,
          rowLabels=rows,
          colLabels=columns, loc="upper center")

ax.axis("off")

#Gold Scatter - Small scatter to the right
plt.subplot2grid((4,3), (0,2))
plt.scatter(scatter_x, scatter_y)
plt.ylabel('Gold Last')

fig.set_size_inches(w=6, h=5)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明