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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With