Final tick marks missing when defined with np.arange

Viewed 145

I wonder why 6.28 on the x-axis and 2 on the y-axis are not output. I don't want to designate xticks and yticks every day, but how can I solve this?

Here is my code.

import numpy as np

import matplotlib.pyplot as plt

def f(x):
    return np.sin(x)

def g(x):
    return np.cos(3*x)

def h(x):
    return np.sin(x)+np.cos(3*x)

fig = plt.figure()

x = np.linspace(-2*np.pi, 2*np.pi, 100)

plt.plot(x, f(x), color='blue')

plt.plot(x, g(x), color='red')

plt.plot(x, h(x), color='black')

plt.ylim(-2,2)

plt.xlim(-2*np.pi, 2*np.pi)

plt.title('Trigonometric functions',size=20)

plt.xlabel('$x$')

plt.ylabel('$y$')

plt.xticks(np.arange(-2*np.pi,2*np.pi,1/2*np.pi))

plt.yticks(np.arange(-2,2,1))

plt.grid(True)

plt.show()
1 Answers

numpy.arange returns numbers in the half-open interval [start, stop). So the stop value you supply is not included, which explains your missing ticks. From the docs:

numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

Return evenly spaced values within a given interval.

Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.

For example:

In [2]: np.arange(-2*np.pi, 2*np.pi, 1/2*np.pi)
Out[2]: 
array([-6.28318531, -4.71238898, -3.14159265, -1.57079633,  0.        ,
        1.57079633,  3.14159265,  4.71238898])

In [3]: np.arange(-2, 2, 1)
Out[3]: array([-2, -1,  0,  1])

So, in answer to your question, you need to include one value above the final value you want to display in your ticks. For example:

In [4]: np.arange(-2*np.pi, 2.5*np.pi, 1/2*np.pi)
Out[4]: 
array([-6.28318531, -4.71238898, -3.14159265, -1.57079633,  0.        ,
        1.57079633,  3.14159265,  4.71238898,  6.28318531])

In [5]: np.arange(-2, 3, 1)
Out[5]: array([-2, -1,  0,  1,  2])

And in your code, you just replace the xticks and yticks lines as:

plt.xticks(np.arange(-2*np.pi, 2.5*np.pi, 1/2*np.pi))
plt.yticks(np.arange(-2, 3, 1))

enter image description here

Related