Search code examples
pythonpython-3.xmatplotlibf-string

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


Firstly,

import matplotlib.pyplot as plt
import matplotlib

In an elementary example on how to plot with matplotlib in our lecture I encountered the following line

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

What I have tried

In the 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 here that also r seems to be a valid option. Also, I discovered in this example that the "parameter" r can also be used in plt.title, but also in the corresponding documentation I didn't find anything.

Entire Code

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)

enter image description here


Solution

  • As others have mentioned, the f in your code is probably a leftover from an f-string. You can read more on f-strings here.

    As you mentioned, you can also find an r (or R) before a string. This defines a raw string. Raw strings are raw string literals that treat backslash (\) as a literal and not as an escape character.

    Example:

    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)
    

    The above code will print out:

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

    You can read more about raw string here.