在python中创建一个表

时间:2015-03-30 12:47:21

标签: python matplotlib

我正在尝试在python中创建一个表,我可以将其放入我在LaTeX中编写的报告中。我已经尝试使用matplotlib来做到这一点,但我得到以下内容...... enter image description here

如果有人知道如何修复我的代码,或者如果有更好的方法,我将不胜感激。这是我用来生成这个代码的代码:

columns=('Temporary ID','ID')
tabledata=[]
for i in range(0,len(ID_mod)):
    tabledata.append([ID_mod[i],sort_ID2[i]])
plt.figure()
plt.table(cellText=tabledata,colLabels=columns)
plt.savefig('table.png')

2 个答案:

答案 0 :(得分:2)

我强烈建议使用LaTeX内置的表格支持。有许多选项可以美化表格,例如booktabs包。更多信息和选项here

答案 1 :(得分:1)

以下是一些用于生成LaTeX表的简单示例函数;

In [1]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def header(align, caption, label=None, pos='!htbp'):
:    """
:    Return the start for a standard table LaTeX environment that contains a
:    tabular environment.
:
:    Arguments:
:    align -- a string containing the LaTeX alignment directives for the columns.
:    caption -- a string containing the caption for the table.
:    label -- an optional label. The LaTeX label will be tb:+label.
:    pos -- positioning string for the table
:    """
:    rs =  r'\begin{table}['+pos+']\n'
:    rs +=  '  \\centering\n'
:    if label:
:        rs += r'  \caption{\label{tb:'+str(label)+r'}'+caption+r'}'+'\n'
:    else:
:        rs += r'  \caption{'+caption+r'}'+'\n'
:    rs += r'  \begin{tabular}{'+align+r'}'
:    return rs
:
:def footer():
:    """
:    Return the end for a standard table LaTeX environment that contains a
:    tabular environment.
:    """
:    rs =  r'  \end{tabular}'+'\n'
:    rs += r'\end{table}'
:    return rs
:
:def line(*args):
:    """
:    Return the arguments as a line in the table, properly serparated and
:    closed with a double backslash.
:    """
:    rs = '  '
:    sep = r' & '
:    for n in args:
:        rs += str(n)+sep
:    rs = rs[:-len(sep)]+r'\\'
:    return rs
:--

如果打印函数的输出,您将看到它是LaTeX代码;

In [2]: print(header('rr', 'Test table'))
\begin{table}[!htbp]
  \centering
  \caption{Test table}
  \begin{tabular}{rr}

In [3]: print(line('First', 'Second'))
  First & Second\\

In [4]: print(line(12, 27))
  12 & 27\\

In [5]: print(line(31, 9))
  31 & 9\\

In [6]: print(footer())
  \end{tabular}
\end{table}

运行相同的代码,但不打印返回的值;

In [7]: header('rr', 'Test table')
Out[7]: '\\begin{table}[!htbp]\n  \\centering\n  \\caption{Test table}\n  \\begin{tabular}{rr}'

In [8]: line('First', 'Second')
Out[8]: '  First & Second\\\\'

In [9]: line(12, 27)
Out[9]: '  12 & 27\\\\'

In [10]: line(31, 9)
Out[10]: '  31 & 9\\\\'

In [11]: footer()
Out[11]: '  \\end{tabular}\n\\end{table}'

将这些函数的ouptut写入文件,并使用LaTeX中的\input mechanisn将其包含在主LaTeX文件中。