Sunday, August 28, 2022

How to create axes labels in Matplotlib plot?

\(x\) and \(y\) axes are defined using commands matplotlib.pyplot.xlabel("label_name") and matplotlib.pyplot.ylabel("label_name2"). The full form of the "xlabel" command can be written as:
matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, loc=None, **kwargs)
As seen the arguments of the xlabel function are xlabel, fontdict,labelpad, loc, and **kwargs. The xlabel is the label text so the type of xlabel variable is the string. The labelpad value represents the spacing in points from the Axes bounding box including ticks and tick labels. If set to None then the default value is 4.0. The loc argument represent the label position which can be 'left', 'center', and 'right'. If None is specified then the default value is 'center'. The **kwargs allows us to pass a variable number of keyword arguments to the Python function. This will be useful if we want to change for example the color of the axes label then we will type color = "red".
Example 1 - Plot the function \(y(t) = \sin(t)\) using matplotlib and show the label \(t\) on the x axis using the matplotlib.pyplot.xlabel function.
Solution: - Before creating the plot the x and y coordinates have to be generated. This will be done using the numpy library and after the library is imported the x coordinates will be created as a list in the range from 0 to 20.01 with step 0.01 (arbitrary step size) using numpy.arange function and the list will be assigned to the t variable. Then the y coordinates will be generated as a list using numpy.sin function.
import numpy as np
t = np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
After the x and y coordinates of \(y(x)\) function are generated the matplotlib library can be used to plot the figure. In this case, the first step is to import the library and then set the figsize to \(12\times 8 [\mathrm{in}]\) using the plt.figure function. Then plot the function using the matplotlib.pyplot.plot command, and make the grid visible using matplotlib.pyplot.grid function.
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
To show the label on x axis we will use the matplotlib.pyplot.xlabel command and set the argument of that function as "t[s]". For this example let's say that t represents the time in seconds. This string is the xlabel argument of xlabel function. The labelpad is by default set to None which means that is equal to 4.0 points i.e spacing from the Axes bounding box including ticks and tick labels. This label will be centered since the loc argument by default is 'center'. To show the plot we need the function matplotlib.pyplot.show().
plt.xlabel("t[s]")
plt.show()
The entire code created in this example is given below.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("t[s]")
plt.show()
The result of the Exmaple 1 code is shown in Figure 1.
Figure 1 - Plot of \(y=\sin(t)\) function with xlabel set to t[s].
As seen from previous figure (Figure x) the plt.xlabel("t[s]") function added the label on \(x\) axis named \(t[s]\). The xlabel can be a math expression and to do this simply type "$expression$". For example instead of "t[s]" we will write "$t$ [s]"in plt.xlabel function.
Example 2 - Using data from Example 1 plot the function using matplotlib and set the xlabel argument as "$t$ [s]".
Solution: Copy the code from the Example 1 and change the plt.xlabel argument from "t[s]" to "$t$ [s]".
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]")
plt.show()
The result of the Example 2 code is shown in Figure 2.
Figure 2 - The plot of \(y(t)\) function with xlabel set to "$t$ [s]".
As seen in Figure 2 the variable \(t\) is in a different format than the rest of the xlabel.
The fontdict argument is the second argument of the xlabel/ylabel function. The fontdict is a dictionary and default value is None. A fontdict can be used to override the default text properties. If fontdict is None, the default font definition is determined by plt.rc parameters.
Example 3 Plot the function \(y(t) = \sin(t)\) using matplotlib library and show the xlabel with Times New Roman font family in red color and the size of the font set to 20.
Solution: For this example after the t and y lists are generated the font dictionary will be created with previously mentioned attributes.
font = {'family': 'Times New Roman',
'color': 'red',
'size': 20}
To apply the font changes in plt.xlabel() besides the "$t$ [s]" we have to include fontdict = font.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
font = {'family': 'Times New Roman',
'color': 'red',
'size': 20}
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]", fontdict=font)
plt.show()
The result of the previous code is shown in Figure 3.
Figure 3 - The plot of \(y(t)\) function with xlabel set to "$t$ [s]" and fontdict set to Times New Roman, color = 'red' and font size = 20
The labelpad represents a spacing in points from the axes bounding box including ticks and tick labels. The labelpad is a scalar, and the default value is None i.e. set by plt.rc parameters to 4.0.
Example 4 Plot the function \(y(t) = \sin(t)\) with argument labelpad of matplotlib.pyplot.xlablel function set to 20.
Solution: In this example we will use the program code from Exmaple 3 and modify the xlabel function by setting the labelpad value to 20.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
font = {'family': 'Times New Roman',
'color': 'red',
'size': 20}
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]", fontdict=font,labelpad=20.0)
plt.show()
The result of the previous code is shown in Figure 4.
Figure 4 - The plot of \(y(t)\) function with xlabel labelpad set to 20.0.
The location of the xlabel can be set with the definition of the xlabel function argument loc. The loc can be set 'left', 'center', and 'right'. The default value is 'center'.
Example 5 Plot the function \(y(t) = \sin(t)\) with different positions of x axis label.
Solution: The loc argument of matpltolib.pyplot.xlabel function is by default set to 'center'. However, the value of this parameter can be 'left', 'center', and 'right'. In this example, we will show the results of all three cases. For this example, we will use program code from Example 4. The code with the xlabel set to the left is shown below.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
font = {'family': 'Times New Roman',
'color': 'red',
'size': 20}
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]", fontdict=font,labelpad=20.0,loc="left")
plt.show()
The result of the previous example is shown in Figure 5.
Figure 5 - The plot of \(y(t)\) function with xlabel location set to left.
If the loc should be the position to the right then in the xlabel function we should type loc="right". The example of positioning the xlabel to the right is given below.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
font = {'family': 'Times New Roman',
'color': 'red',
'size': 20}
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]", fontdict=font,labelpad=20.0,loc="right")
plt.show()
The result of the previous code is shown in Figure 6.
Figure 6 - The plot of \(y(t)\) function with xlabel location set to right.

The same commands are valid for matplotlib.pyplot.ylabel command. The general form of the ylabel command can be written as:
matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None,loc=None, **kwargs)
Now we will set xlabel and ylabel in Times New Roman font style with font size 20. Both labels will be centered. The code for this example is given below.
import numpy as np
import matplotlib.pyplot as plt
t=np.arange(0,20.01,0.01)
y = [np.sin(t[i]) for i in range(len(t))]
font = {'family': 'Times New Roman',
'size': 20}
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("$t$ [s]", fontdict=font,labelpad=20.0,loc="center")
plt.ylabel("$y(t)$ [m]", fontdict=font,labelpad=20.0,loc="center")
plt.show()
The result of the previous code is shown in Figure 7.
Figure 7 - The plot of \(y(t)\) function with xlabel and ylabel.

No comments:

Post a Comment