Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render output of Pandas 'to_latex' method in a matplotlib plot

Python Pandas DataFrame has a to_latex method:

import pandas as pd
from numpy import arange

a = pd.DataFrame(arange(4))
a.to_latex()

Output:

'\begin{tabular}{|l|c|c|}\n\hline\n{} & 0 \\\n\hline\n0 & 0 \\\n1 & 1 \\\n2 & 2 \\\n3 & 3 \\\n\hline\n\end{tabular}\n'

I would like to overlay this table on a matplotlib plot:

import pylab as plt
import matplotlib as mpl

mpl.rc('text', usetex=True)
plt.figure()
ax=plt.gca()

plt.text(9,3.4,a.to_latex(),size=12)
plt.plot(y)
plt.show()

However, I get this error:

RuntimeError: LaTeX was not able to process the following string: '\begin{tabular}{|l|c|c|}'

My question is:

How do I render output of Pandas 'to_latex' method in a matplotlib plot?

like image 649
vg425 Avatar asked Feb 23 '13 14:02

vg425


1 Answers

The problem is that matplotlib doesn't handle multiline latex strings well. One way to fix it is to replace the newline characters in the latex string with spaces. That is, do something like this:

ltx = a.to_latex().replace('\n', ' ')
plt.text(9, 3.4, ltx, size=12)
like image 158
Warren Weckesser Avatar answered Oct 09 '22 00:10

Warren Weckesser