I'm trying to display some statistics in a matplotlib text box in a tabular format.
Getting the text box to display works fine, and tabularizing data outside a plot with print statements using string formatting align operands ('>', '<') works fine, but once I wrap the formatted strings in ax.text(), the alignment seems to get ignored.
For example:
import matplotlib.pyplot as plt
import numpy as np
def plot_histo(data, stats):
fig, ax = plt.subplots()
n, bins, patches = plt.hist(data, bins=16, alpha=0.5)
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
ax.text(0.8, 0.85, stats, transform=ax.transAxes, bbox=props)
plt.show()
data = np.random.normal(size=100)
stats = '\n'.join([
'{:<8}{:>4}'.format('n:', len(data)),
'{:<8}{:>4.2f}'.format('Mean:', np.mean(data)),
'{:<8}{:>4.2f}'.format('SD:', np.std(data)),
])
plot_histo(data, stats)
plots like
But, using a print statement:
print(stats)
outputs the desired, aligned, tabular format.
n: 100
Mean: 0.01
SD: 0.95
Any ideas on how to get the tabular formatting in a text box? Using a monospaced font is undesirable for the end application.


tableinstead.