如何在Matplotlib的情节上放置一张桌子?

时间:2011-12-15 17:46:53

标签: python matplotlib

我没有成功地使matplotlib表命令工作。以下是我想做的一个例子:

任何人都可以帮忙处理表格构造代码吗?

import 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
plt.text(11,4.1,'Table Title',size=8)
plt.plot(y)
plt.show()

2 个答案:

答案 0 :(得分:46)

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()

结果是:

enter image description here

请记住,这是一个快速的例子;你应该能够通过播放文本坐标来正确放置桌子。如果您需要更改字体等,请参阅docs

更新:pyplot.table

上的更多信息

根据documentationplt.table为当前轴添加了一个表格。从显而易见的来源来看,图表上的表格位置是根据轴确定的。可以使用关键字Y(上图),top(上半部分),upper(中间),centerlower来控制bottom坐标在下半部分)和X(下图)。 left坐标由关键字righttop left控制。这两种作品的任意组合,例如: center rightbottomimport 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() 中的任何一个都可以使用。

所以最接近你想要的图表可以用:

{{1}}

这会给你

enter image description here

希望这有帮助!

答案 1 :(得分:6)

我不确定以前的答案是否满足您的问题,我也在寻找一种方法来添加表格,并找到克服“loc”限制的可能性。您可以使用边界框来控制表的确切位置(这仅包含表创建但应该足够):

        tbl = ax1.table(
            cellText=[["a"], ["b"]],
            colWidths=[0.25, 0.25],
            rowLabels=[u"DATA", u"WERSJA"],
            loc="bottom", bbox=[0.25, -0.5, 0.5, 0.3])

        self.ui.main_plot.figure.subplots_adjust(bottom=0.4)

结果是(我没有发布图片的声誉,所以这里是一个链接):http://www.viresco.pl/media/test.png

请注意,bbox单位已标准化(不是绘图比例)。