为 matplotlib 定义标题 table

Define title to a matplotlib table

我有一个由 matplotlib 生成的 table,我想为它插入一个标题。有人知道怎么做吗?

ax = fig.add_subplot(111)
fig = plt.figure(constrained_layout=True)
spec2 = gridspec.GridSpec(ncols=2, nrows=3, figure=fig  )
ax1 = fig.add_subplot(spec2[0, 0])
ax2 = fig.add_subplot(spec2[0, 1])
ax1.axis('off')
ax2.axis('off')

table_data=[
["Ni_Tot ", "NN", "2.5%" , round(df.NN_Ni_Tot.quantile(0.025),3)],
["N. of Samples", count,  "5%" , round(df.NN_Ni_Tot.quantile(0.05),3)],
["Minimum", round(min(df['NN_Ni_Tot'].apply(pd.to_numeric)),3), "25%" , round(df.NN_Ni_Tot.quantile(0.25),3)],
["Maximum", round(max(df['NN_Ni_Tot'].apply(pd.to_numeric)),3), "Median", round(df.NN_Ni_Tot.quantile(0.5),3)],
["Average", round(statistics.mean(df['NN_Ni_Tot'].apply(pd.to_numeric)),3),"75%", round(df.NN_Ni_Tot.quantile(0.75),3)],
["Variance", round(df['NN_Ni_Tot'].var(),2), "95%", round(df.NN_Ni_Tot.quantile(0.95),3)],
["Std Deviation", round(df['NN_Ni_Tot'].std(),2),"97.5%", round(df.NN_Ni_Tot.quantile(0.975),3)],]


table = ax1.table(cellText=table_data, loc='center', cellLoc='center')
table.set_fontsize(14)
table.scale(1.5,1.4)

https://i.stack.imgur.com/P27Vu.png

ax.set_title("Your title")

Relevant documentation

ax1.set_title("Your title")

上面的代码行有效,但标题位于 table 的中间,与数据重叠。所以我不得不手动调整它

ax1.set_title("NN_NI", fontsize=8, y=1.8, pad=-14)