Reputation: 314
I'm trying to make a table in python which I can put into a report I'm writing in LaTeX . I've tried to use matplotlib to do this but I get the following...
If anyone has any idea how I can fix my code, or if theres a better approach I'd be grateful. Here's the code I'm using to generate this:
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')
Upvotes: 0
Views: 941
Reputation: 43495
The following are some simple example functions for generating LaTeX tables;
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
:--
If you print the output of the functions, you'll see it is LaTeX code;
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}
Running the same code, but without printing the returned values;
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}'
Write the ouptut of these functions to a file, and use the \input
mechanisn in LaTeX to include it in your main LaTeX file.
Upvotes: 1