Search code examples
pythonmatplotlibf-string

In Matplotlob writing mathematical expressions with f-literals; how to deal with the raise to the power (^)


I want to display certain equations on a Matplotlob plot. Following Writing mathematical expressions with Matplotlob I wrote the following. The coefficients for the question are also only available at runtime, so I also use python f-string literals. But they are somewhat incompatible since { has different meaning in the two cases. Here is a concrete example:

import matplotlib.pyplot as plt

a = 0.3543545
b = 6.834
c = -126.732

s0 = r'$\alpha_i > \beta_i$'
s1 = r"$0.354 * x^{6.834} -126.732 $" # Works as expected
s2 = fr"${a:.3f} * x^{{b:.3f}} {c:+.3f}$" # Doesn't work; Same as S1 but with f-string literals
s3 = fr"${a:.3f} * x^{b:.3f} {c:+.3f}$" # Doesn't work;


plt.text(0.1, 0.9, s0)
plt.text(0.1, 0.8, s1)
plt.text(0.1, 0.7, s2)
plt.text(0.1, 0.6, s3)
plt.show()

Plot with equations

So how to reproduce the same results with s2 or s3 as s1 when using f-string literals?


Solution

  • In the f-string, curly braces need to be represented by two layers, so you need three layers to meet your requirements:

    >>> a = 100
    >>> f'{{a}}'
    '{a}'
    >>> f'{{{a}}}'
    '{100}'