Sunday, August 28, 2022

How to specify axes range in matplotlib plot?

The axes range is specified with matplotlib.pyplot.xlim(specify range) or with matplotlib.pyplot.ylim(specify range). The general form of both functions can be written as:
matplotlib.pyplot.xlim(*args, **kwargs)
matplotlib.pyplot.ylim(*args, **kwargs)
In previous lines of code, the *args allows us to pass the variable number of non-keyword arguments to function. The **kwargs allows us to pass the variable length of keyword arguments to the function. Usually, the xlim and ylim are defined as:
plt.xlim(lower_value, upper_value)
plt.ylim(lower_value, upper_value)
where lower_value and upper_value are numbers (type: float) that define the limits of xlim and ylim in which we want to show the plot.
Example Create the plot of \(y(t) = \sin(t)\) function and set limit of x-axis in range from 0 to 20 and limit on y-axis from -1.0 to 1.0.
Solution: First we will create a plot to see the plot without the limits. To generate the data that will be plotted we have to import the numpy library. Then generate x-coordinates in range from 0 to 20.01 with step size of 0.01 (arbitrary step) using np.arange function and assign it to t variable. The next step is to generate the y-coordinates as a list using the x-coordinate values and the numpy function sin().
import numpy as np
t = np.arange(0, 20.01, 0.01)
y = [np.sin(t[i]) for i in range(len(t))]
The next step is to plot the function with a grid with xlables and ylabels set to "t [s]" and "y(t) [m]".
import matplotlib.pyplot as plt
plt.figure(figsize=(12,8))
plt.plot(t,y)
plt.grid(True)
plt.xlabel("t [s]")
plt.ylabel("y(t) [m]")
plt.show()
The entire code created in this example, so far, 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.ylabel("y(t) [m]")
plt.show()
The result of the previous code is shown in Figure 1.
Figure 1 - The plot of \(y(t)\) function without defined x and y limits.
Now we are going to set the xlim from 0 to 20 and ylim from -1.0 and 1.0 by typing:
plt.xlim(0,20)
plt.ylim(-1.0, 1.0)
The entire code 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.ylabel("y(t) [m]")
plt.xlim(0,20)
plt.ylim(-1,1)
plt.show()
The result of the previous code is shown in Figure 2.
Figure 2 - The plot of \(y(t)\) function with defined x and y limits.