0

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?

KarateKid
  • 3,138
  • 4
  • 20
  • 39
  • 1
    You need 3 pairs of `{}`. One to enable replacing its contents with variable, and another two to put literal `{}` characters in the f-string. – matszwecja Apr 27 '22 at 11:15

1 Answers1

2

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}'
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31