I would like to show a (LaTeX) table in a Matplotlib graph. I have generated the LaTeX source for the table by styling a Pandas DataFrame
, and am attempting to add that to my graph using the Axes.text
method. However, the code is failing with what seems to be some kind of LaTeX interpretation error.
Here's what I have:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame(np.random.randn(10000, 4) * np.array([1, 2, 2, 0.5]) + np.array([0, 4, 9, 11]),
columns=['first', 'second', 'third', 'fourth'])
stats = df.describe()
stats.index = [idx.replace('%', 'p') for idx in stats.index]
styled = stats.style\
.background_gradient(cmap=sns.blend_palette(['xkcd:red', 'white', 'xkcd:green'], as_cmap=True),
vmin=-15, vmax=15,
subset=pd.IndexSlice[['mean', 'min', '25p', '50p', '75p', 'max'], :])\
.background_gradient(cmap=sns.blend_palette(['white', 'xkcd:purple'], as_cmap=True),
vmin=0, vmax=3, subset=pd.IndexSlice['std', :])\
.format(lambda v: f'{v:0.2f}')\
.format(lambda v: f'{v:0.0f}', subset=pd.IndexSlice['count', :])
s = styled.to_latex(
clines="skip-last;data",
convert_css=True,
position_float="centering",
multicol_align="|c|",
hrules=True
).replace('\n', ' ')
plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{booktabs} \usepackage{etoolbox} \usepackage{multirow} \usepackage[table]{xcolor} \usepackage{colortbl} \usepackage{siunitx} \usepackage{longtable} \usepackage{graphics}')
fig, ax = plt.subplots(1, 1, figsize=(10, 6))
df.plot(kind='hist', ax=ax, histtype='stepfilled', alpha=0.4, bins=50)
ax.set_xlim([-6, 15])
ax.legend(loc='upper right')
ax.text(0.02, 0.98, s, ha='left', va='top', transform=ax.transAxes)
The graphing works fine except for the inclusion of the styled table. I get this result, which is clearly not correct.
I'm hoping for something more like this to show up on the Axes.