f 在 plt.ylabel(f'g(x)') 中的作用是什么?

What does the f do in plt.ylabel(f'g(x)')?

首先,

import matplotlib.pyplot as plt
import matplotlib

在我们讲座中关于如何使用 matplotlib 绘图的基本示例中,我遇到了以下行

plt.ylabel(f'g(x)')

我试过的

documentation there's no mention of an additional parameter to be inserted before the actual label text. I further checked out examples where plt.ylabel was used and discovered herer 似乎也是一个有效选项。 另外,我在 this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation 中发现我没有找到任何东西。

完整代码

plt.figure(figsize=(6,4))
X = np.arange(0,2*np.pi,0.2)
plt.plot(X,np.sin(X),'o-',label='$\sin(x)$')
plt.plot(X,np.cos(X),'*-',c='g', label='$\cos(x)$')
plt.ylabel(f'f(x)' rotation=0)
plt.grid() # adds grid 
_=plt.legend(loc=3)

f代表格式字符串 你可以在任何地方使用它不是 特定于 matplotlib

示例:

x = 12
print(f'Hello {x}') # That will print 'Hello 12'

还有:

print(f'Hello') # Also Works Just fine That will print 'Hello'

检查是否是剩余f

正如其他人所提到的,您代码中的 f 可能是 f-string 的剩余部分。你可以阅读更多关于 f-strings here.

如您所述,您还可以在字符串前找到 r(或 R)。这定义了一个 原始字符串 。原始字符串是将反斜杠 (\) 视为文字而不是转义字符的原始字符串文字。

示例:

dummy_str = "This is a \n normal string"
print(dummy_str)

raw_dummy_str = r"This is a \n raw string"
print(raw_dummy_str)

上面的代码会打印出:

This is a
 normal string
This is a \n raw string

您可以阅读有关原始字符串的更多信息 here