如何在matplotlib中的F弦表达式中使用乳胶;方程中没有变量
我正在尝试为情节制作标题,但是标题包括一个变量,我正在使用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:
but I can't seem to make it work with an f-string variable also in the title.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
必须这样做:
因为您需要使用
{
和}
字符,所以它们需要加倍,以便将它们解释为文字字符。这将阻止其解释括号之间的内容为Python表达式。因此,它将不再抱怨后斜线或未定义变量。另外,可以将其放入单独的字符串中,以避免将括号加倍。在我看来,这更可读。
It has to be done like this:
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.