在matplotlib图中渲染Pandas'to_latex'方法的输出

vg4*_*425 4 python latex matplotlib pandas

Python Pandas DataFrame有一个to_latex方法:

import pandas as pd
from numpy import arange

a = pd.DataFrame(arange(4))
a.to_latex()
Run Code Online (Sandbox Code Playgroud)

输出:

'\ 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'

我想在matplotlib图上叠加这个表:

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()
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

RuntimeError:LaTeX无法处理以下字符串:'\ begin {tabular} {| l | c | c |}'

我的问题是:

如何在matplotlib图中渲染Pandas'to_latex'方法的输出?

War*_*ser 5

问题是matplotlib不能很好地处理多行乳胶串.修复它的一种方法是用空格替换latex字符串中的换行符.也就是说,做这样的事情:

ltx = a.to_latex().replace('\n', ' ')
plt.text(9, 3.4, ltx, size=12)
Run Code Online (Sandbox Code Playgroud)