如何在matplotlib中的F弦表达式中使用乳胶;方程中没有变量

发布于 2025-02-11 06:39:18 字数 715 浏览 3 评论 0原文

我正在尝试为情节制作标题,但是标题包括一个变量,我正在使用F-string插入该变量,但它也包括乳胶表达式。我要么遇到一个错误,即F-string表达式不采用\字符,否则它试图将方程式中的内容读取为变量,并抱怨它没有定义。

我正在尝试的代码看起来像这样:

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

此代码会给我错误:“ F-string表达式部分不能包括后斜切”,当我尝试此操作时(请注意额外的括号):

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

我得到此错误:“名称“ B”不是定义的“

我希望它仅显示B/A的平方根,其中B和A只是字母,而不是变量,因此它看起来像下面的图:

但是,我似乎也无法与标题中的F弦变量一起使用。

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}}
quot;)
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}}}
quot;)
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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薯片软お妹 2025-02-18 06:39:18

必须这样做:

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

因为您需要使用{}字符,所以它们需要加倍,以便将它们解释为文字字符。这将阻止其解释括号之间的内容为Python表达式。因此,它将不再抱怨后斜线或未定义变量。

另外,可以将其放入单独的字符串中,以避免将括号加倍。在我看来,这更可读。

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

It has to be done like this:

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

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}}
quot;
plt.title(f"This is a {test}: {tex}")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文