AFAIK,您不能任意仅使用原生 matplotlib 功能在 matplotlib 图上放置表格。您可以做的是利用latex text rendering 的可能性。但是,为了做到这一点,您的系统中应该有工作 latex 环境。如果你有,你应该能够生成如下图:
import pylab as plt
import matplotlib as mpl
mpl.rc('text', usetex=True)
plt.figure()
ax=plt.gca()
y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1]
#plt.plot([10,10,14,14,10],[2,4,4,2,2],'r')
col_labels=['col1','col2','col3']
row_labels=['row1','row2','row3']
table_vals=[11,12,13,21,22,23,31,32,33]
table = r'''\begin{tabular}{ c | c | c | c } & col1 & col2 & col3 \\\hline row1 & 11 & 12 & 13 \\\hline row2 & 21 & 22 & 23 \\\hline row3 & 31 & 32 & 33 \end{tabular}'''
plt.text(9,3.4,table,size=12)
plt.plot(y)
plt.show()
结果是:
请记住,这是一个简单粗暴的例子;您应该能够通过使用文本坐标正确放置表格。如需更改字体等,也请参考docs。
更新:更多关于pyplot.table
根据documentation,plt.table向当前坐标区添加了一个表格。从来源很明显,图表上的表格位置是相对于轴确定的。 Y坐标可以通过关键字top(上图)、upper(上半部分)、center(中间)、lower(下半部分)和bottom(下图)。 X 坐标由关键字left 和right 控制。两种作品的任意组合,例如top left、center right 和 bottom 中的任何一个都可以使用。
所以最接近你想要的图表可以用:
import matplotlib.pylab as plt
plt.figure()
ax=plt.gca()
y=[1,2,3,4,5,4,3,2,1,1,1,1,1,1,1,1]
#plt.plot([10,10,14,14,10],[2,4,4,2,2],'r')
col_labels=['col1','col2','col3']
row_labels=['row1','row2','row3']
table_vals=[[11,12,13],[21,22,23],[31,32,33]]
# the rectangle is where I want to place the table
the_table = plt.table(cellText=table_vals,
colWidths = [0.1]*3,
rowLabels=row_labels,
colLabels=col_labels,
loc='center right')
plt.text(12,3.4,'Table Title',size=8)
plt.plot(y)
plt.show()
这给了你
希望这会有所帮助!