How to force Matplotlib to display the "endpoint ticks" of a line chart

I’m a beginning learner to Matplotlib and I’m confused about how to plot the “endpoint ticks” of a given line chart with Matplotlib.

Here is my sample script:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from matplotlib import rc
rc(‘mathtext’, default=‘regular’)
matplotlib.rcParams.update({‘font.family’: ‘Times New Roman’})

fig, ax = plt.subplots()
ax.grid()
x = np.linspace(-np.pi, np.pi, 100)
x_ticks = np.arange(-3, 3, 0.5)
y_ticks = np.arange(-1, 1, 0.25)
plt.xticks(x_ticks)
plt.yticks(y_ticks)
ax.set_xlabel(‘X Axis’)
ax.set_ylabel(‘Y Axis’)
plt.plot(x, np.sin(x)np.cos(2x + 1), label = ‘Sin() Function’, color = ‘#27408b’, linewidth = 2.5)
plt.legend()

plt.title(“Template Plotting for Sin() Function”)
plt.show()

And my generated plot is shown below:

From this plot, we can find the “endpoint ticks” (x=3.0, y=1/-1) of the chart are missing.

I’ve tried several approaches including add comment “endpoint=True” into the function of np.linspace(), or set “ax.set_xticklabels” and etc. But the issue cannot be resolved properly. So how could I force the Matplotlib to display the endpoint ticks in a line chart? What is the standard approach or the widely used strategy?

1 Like

what is the “endpoint tick”? the max and min of the data? Or the top and bottom of that y axis?

Sorry for the misunderstanding for my post. I mean, I set the X/Y axis range with np.linspace(start, stop, step) or np.arange(start, stop, step) function, but the value of the stop is not included and displayed. Now I have understood that this is not allowed. But I want to know if there are any alternatives?

In addition, I note the range of Y-axis is not strictly follow the settings in original code (means Matplotlib will auto-rescale it by itself), also, is there any approach to force the Matplotlib to visualize it literally?

I’m not completely sure if this is what you’re trying to do, but would manually setting the limits via set_{x,y}lims do the trick?

ax.set_xlim(start, stop)
ax.set_ylim(start, stop)

and possibly with a small margin on the start stop but I don’t think you need it.