4

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?

1 Answer 1

7

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.