How to limit range on x and y axis in matplotlib diagram ?

The minimum working example so far:

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(0,20.01,0.01)

y = np.sin(x)

plt.figure()

plt.plot(x,y)

plt.xlabel("$x$")

plt.ylabel("$sin(x)$")

plt.show()

After running the previous code the following figure is obtained.

Figure 1 – The result of minimum working example (so far)

As seen from Figure 1 the x values are from 0 to 20 however the matplotlib.pyplot is showing values below 0.0 and above 20.0. The similar thing can be noticed for y axis (indicated with sin(x)) where the values are in range from -1.0 up to 1.0 but the matplotlib.pyplot is showing the y axis range below and above aforementioned range. The idea is to limit the x range from 0 to 20.0 and extend the y range from -1.5 up to 1.5.  

To set the x in range from 0 to 20.00, and y from -1.5 up to 1.5, type in the following code just after plt.ylabel but before plt.show().

plt.xlim(0,20.00)

plt.ylim(-1.5,1.5)

By typing this two lines of code and after running the python code the following figure should be obtained.

Figure 2 – The result of xlim (0 - 20.0) and ylim (-1.5 - 1.5) command

The entire final form of minimum working example.

 import matplotlib.pyplot as plt

import numpy as np

x = np.arange(0,20.01,0.01)

y = np.sin(x)

plt.figure()

plt.plot(x,y)

plt.xlabel("$x$")

plt.ylabel("$sin(x)$")

plt.xlim(0,20.0)

plt.ylim(-1.5,1.5)

plt.show()

Nema komentara:

Objavi komentar