Render output of Pandas 'to_latex' method in a matplotlib plot
Python Pandas DataFrame具有
1 2 3 4 5 | import pandas as pd from numpy import arange a = pd.DataFrame(arange(4)) a.to_latex() |
输出:
'\\begin{tabular}{|l|c|c|}\
\\hline\
{} & 0 \\\\\
\\hline\
0 & 0
\\\\\
1 & 1 \\\\\
2 & 2 \\\\\
3 & 3
\\\\\
\\hline\
\\end{tabular}\
'
我想将此表格叠加在matplotlib图上:
1 2 3 4 5 6 7 8 9 10 | 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() |
但是,出现此错误:
RuntimeError: LaTeX was not able to process the following string:
'\\begin{tabular}{|l|c|c|}'
我的问题是:
如何在matplotlib图中渲染Pandas \\'to_latex \\'方法的输出?
问题在于matplotlib无法很好地处理多行乳胶字符串。解决该问题的一种方法是用空格替换乳胶字符串中的换行符。也就是说,执行以下操作:
1 2 3 | ltx = a.to_latex().replace('\ ', ' ') plt.text(9, 3.4, ltx, size=12) |