Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display LaTeX f-strings in matplotlib [duplicate]

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.

like image 375
will.mendil Avatar asked Feb 10 '20 12:02

will.mendil


People also ask

How to write string with f in Python?

Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.

Does F-string call str or repr?

f-strings in Python don't use __str__ or __repr__ . They use __format__ . So to get the same result as f'{Thing. A}' , you'd need to call format(Thing.

Can you use functions in F-strings?

Calling functions with f-stringPython f-strings enables us to call functions within it. Thus, optimizing the code to an extent. The same way can be used for creating lambda functions within f-string bracets.


1 Answers

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.

like image 57
CDJB Avatar answered Sep 18 '22 15:09

CDJB