如何在 Matplotlib 中绘制一个表格
Suraj Joshi
2020年11月7日
Matplotlib
我们可以使用 matplotlib.pyplot.table 方法在 Matplotlib 中绘制一个表格。
matplotlib.pyplot.table() 方法
matplotlib.pyplot.table() 语法
matplotlib.pyplot.table(
cellText=None,
cellColours=None,
cellLoc="right",
colWidths=None,
rowLabels=None,
rowColours=None,
rowLoc="left",
colLabels=None,
colColours=None,
colLoc="center",
loc="bottom",
bbox=None,
edges="closed",
**kwargs
)
示例: 在 Matplotlib 中使用 matplotlib.pyplot.table() 方法绘制一个表格
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
data = [[1, 2, 3], [5, 6, 7], [8, 9, 10]]
column_labels = ["Column 1", "Column 2", "Column 3"]
ax.axis("tight")
ax.axis("off")
ax.table(cellText=data, colLabels=column_labels, loc="center")
plt.show()
输出:

该方法从 table() 方法中作为 cellText 参数传递的数据生成一个表格。列名可以用 colLabels 参数指定,loc="center"将表格置于各轴的中心。
我们也可以通过 Pandas DataFrame 和 NumPy Arrays 作为 cellText 参数来生成表格。
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
data = [[1, 2, 3], [5, 6, 7], [8, 9, 10]]
column_labels = ["Column 1", "Column 2", "Column 3"]
df = pd.DataFrame(data, columns=column_labels)
ax.axis("tight")
ax.axis("off")
ax.table(
cellText=df.values, colLabels=df.columns, rowLabels=["A", "B", "C"], loc="center"
)
plt.show()
输出:

这个过程从 DataFrame df 生成表格。我们将 df 的值作为 cellText 参数,将 df 的列名作为 colLabels 参数。rowLabels 值作为表的行标签。
为了区分表中的行标签和列标签,要对这些特定字段进行不同的样式。
import pandas as pd
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
data = [[1, 2, 3], [5, 6, 7], [8, 9, 10]]
column_labels = ["Column 1", "Column 2", "Column 3"]
df = pd.DataFrame(data, columns=column_labels)
ax.axis("tight")
ax.axis("off")
ax.table(
cellText=df.values,
colLabels=df.columns,
rowLabels=["A", "B", "C"],
rowColours=["yellow"] * 3,
colColours=["yellow"] * 3,
loc="center",
)
plt.show()
输出:

在这里,我们将行标签和列标签用黄色来区分这些字段与表的其他部分;这是用参数 rowColours 和 colColours 来完成的。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn