我需要在 matplotlib 中重新創建這個結構

import matplotlib.pyplot as plt
fig, (ax1, ax2, ax3, ax4) = plt.subplots(ncols=1, nrows=4)
# fig.tight_layout()
ax1.axis("off")
ax2.axis("off")
ax3.axis("off")
ax4.axis("off")
ax1.table(cellText=[["A", "B", "C", "D", "E", "F"]])
ax2.table(cellText=[[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3],
[4, 4, 4, 4, 4, 4],
[5, 5, 5, 5, 5, 5],
[6, 6, 6, 6, 6, 6],
[7, 7, 7, 7, 7, 7],
[8, 8, 8, 8, 8, 8],
[9, 9, 9, 9, 9, 9]])
ax3.table(cellText=[[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6]])
ax4.table(cellText=[[1, 2, 3, 4, 5, 6]])
plt.show()
這是我到目前為止所擁有的,但是表格重疊并且不可用。所以我的問題是如何在matplotlib中實作這個表結構?
uj5u.com熱心網友回復:
您遇到的問題是subplots假設您所有的表都是相同的大小。由于情況并非如此,因此您最終會得到比基礎Axes物件更大的表。
如果您的情況是您提前準備好表格,那么您可以根據行數估算它們的大小。您可以將此資訊傳遞給subplots建構式,以按比例調整回傳的 Axes 的大小,以便每個表都適合它們自己的軸。
在這里,我在一個總體串列中預定義了所有表(主要是為了方便)。然后我可以獲取每個表中的行數并將其傳遞給height_ratiosgridspec 引數,以便每個生成Axes的大小與其各自表中的行數成正比。
然后我可以用表格壓縮回傳的軸并實際插入值。
最后,您應該通過loc='center',因此每個表格實際上都被繪制到Axes而不是下方、上方或側面。
import matplotlib.pyplot as plt
tables = [
[["A", "B", "C", "D", "E", "F"]],
[[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3],
[4, 4, 4, 4, 4, 4],
[5, 5, 5, 5, 5, 5],
[6, 6, 6, 6, 6, 6],
[7, 7, 7, 7, 7, 7],
[8, 8, 8, 8, 8, 8],
[9, 9, 9, 9, 9, 9]],
[[1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6]],
[[1, 2, 3, 4, 5, 6]]
]
table_rows = [len(tbl) for tbl in tables]
fig, axes = plt.subplots(
ncols=1, nrows=len(tables),
gridspec_kw={'height_ratios': table_rows}
)
for tbl, ax in zip(tables, axes.flat):
ax.table(cellText=tbl, loc='center')
ax.axis('off')
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/476706.html
標籤:Python matplotlib
