latex-markdown labels on matplotlib

1.9k Views Asked by At

I have a matplotlib chart which I want to annotate with latex markdown.

axs.annotate(s='$r_f = {:.2f}$'.format(r), xy=[2005, 7],
             xycoords="data", fontsize=18)

this works fine, but I want the latex code with more than one letter in the subscript. I need instead $r_{fit}$, but that confuses the internal system of python's format method.

c:\Users\Dean\Dropbox\Dean\Study\_Thesis\2. Paper\code\paper\charts.py in plot_prediction(x, y, data, future_x, future_y, future_data, death)
    141         axs.scatter(x, data, label='Train Data', color=_palette[0])
    142         r, p = pearsonr(y, data)
--> 143         axs.annotate(s=r'$r_{fit} = {:.2f}$'.format(r), xy=[2005, 7],
    144                      xycoords="data", fontsize=18)
    145         # print p

KeyError: 'fit'

I tried many oprions with the escape characters but nothing worked.

1

There are 1 best solutions below

0
On BEST ANSWER

The problem is with the format/string and not matplotlib, I get the error with,

"$r_{fit} = {:.2f}$".format(10.)

 KeyError                                  Traceback (most recent call      last)
<ipython-input-41-2d336f9a0477> in <module>()
----> 1 "$r_{fit} = {:.2f}$".format(10.)

KeyError: 'fit'

The issue is solved in this answer, where they use double braces,

"$r_{{fit}} = {:.2f}$".format(r)

Another simple work around would also be to split the subscripted and format statement,

"$r_{fit}" + " = {:.2f}$".format(r)

which also works as expected.