Search code examples
pythonpython-3.xstringmatplotlibf-string

How to display LaTeX f-strings in matplotlib


In Python 3.6, there is the new f-string to include variables in strings which is great, but how do you correctly apply these strings to get super or subscripts printed for matplotlib?

(to actually see the result with the subscript, you need to draw the variable foo on a matplotlib plot)

In other words how do I get this behaviour:

    var = 123
    foo = r'text$_{%s}$' % var
    text<sub>123</sub>

Using the new f-string syntax? So far, I have tried using a raw-string literal combined with an f-string, but this only seems to apply the subscript to the first character of the variable:

    var = 123
    foo = fr'text$_{var}$'
    text<sub>1</sub>23

Because the { has an ambiguous function as delimiting what r should consider subscript and what f delimits as a place for the variable.


Solution

  • You need to escape the curly brackets by doubling them up, and then add in one more to use in the LaTeX formula. This gives:

    foo = f'text$_{{{var}}}$'
    

    Example:

    plt.figure()
    plt.plot([1,2,3], [3,4,5])
    var = 123
    plt.text(1, 4,f'text$_{{{var}}}$')
    

    Output:

    enter image description here

    Incidentally, in this example, you don't actually need to use a raw-string literal.