2

I'm trying to make a title for a plot, but the title includes a variable, which I'm inserting using an f-string, but it also includes a Latex expression. I either get an error that f-string expressions do not take \ character, or else it's trying to read what's inside the equation as variables and complaining that it's not defined.

The code I'm trying looks something like this:

test = 'TEST'
plt.plot(1234,5678)
plt.title(f"This is a {test}: ${\sqrt{b/a}}$")
plt.show()

This code will give me the error: "f-string expression part cannot include a backslash", and when I try this (note the extra brackets):

test = 'TEST'
plt.plot(1234,5678)
plt.title(f"This is a {test}: ${{\sqrt{b/a}}}$")
plt.show()

I get this error: "name 'b' is not defined"

I want it to just show a square root of b/a, where b and a are just the letters, not variables, so that it looks something like the plot below:

enter image description here

but I can't seem to make it work with an f-string variable also in the title.

1 Answer 1

3

It has to be done like this:

plt.title(f"This is a {test}: ${{\sqrt{{b/a}}}}$")

Since you need to use the { and } characters, they need to be doubled up so that they are interpreted as literal characters. This will prevent it from interpreting the contents between the brackets as a Python expression. Thus, it will no longer complain about the backslash or undefined variables.

Alternatively, it can be put in a separate string to avoid doubling up the brackets. This is more readable in my opinion.

tex = "${\sqrt{b/a}}$"
plt.title(f"This is a {test}: {tex}")
Sign up to request clarification or add additional context in comments.

1 Comment

That worked beautifully, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.