pikachuchameleon
pikachuchameleon

Reputation: 675

Unexpected '{' in field name when doing string formatting using latex in python

I want to insert text inside a latex equation which is actually a title for the plot. In other words, the following is the python code for the title I am using:

import matplotlib.pyplot as plt

x=8
plt.title(r"Actual time-series is $Y_t=\alpha^\top X_t + \beta^\top X_{t-{0}}$".format(x))

plt.show()

The following is the error I received when I implemented the above code:

 Traceback (most recent call last):
  File "switch_systems.py", line 419, in <module>
     plt.title(r"Actual time-series is $Y_t=\alpha^\top X_t + \beta^\top  X_{t-{0}}$".format(x)
   ValueError: unexpected '{' in field name

I want my title to look like Actual time-seris is $Y_t=\alpha^\top X_t + \beta^\top X_{t-8}$, as in the text inside latex to be exactly resemble what it would have looked like had it been written in latex. Is there a trick to do this?

Upvotes: 3

Views: 3419

Answers (1)

tdelaney
tdelaney

Reputation: 77337

You need to escape the literal { that you want to keep in the text by doing {{ and }}

r"Actual time-series is $Y_t=\alpha^\top X_t + \beta^\top X_{{t-{0}}}$".format(8)

results in

Actual time-series is $Y_t=\alpha^\top X_t + \beta^\top X_{t-8}$

Upvotes: 5

Related Questions