How to use xlim() In Python

Using this locate_params() function, no matter how many bins we mention, we will always show the whole plot regardless of the number. Still, if we want only the first three values of the x-axis to visualize, you can use this xlim() and ylim() function to set a limit for the x-axis and y-axis of the plot and then use the locate param to reduce the number of ticks.

Note: If you forget to use the locate_param after this function will not reduce the number of ticks it will still show all the unwanted ticks on your plot. So, make sure you use locate_params() function after this function

Syntax:

matplotlib.pyplot.xlim(*args, **kwargs)

Now, we are going to try and reduce the number of ticks on the x-axis and try to visualize only the first three values of the plot.

Example:

Like the previous example, we are using locate_params() to limit the number of ticks, but before that, we will restrict the number of ticks we have to visualize from the start to end as a tuple.

Python3




# Setting x and y values for the plot
x = [1, 2, 3, 4]
y = [7, 13, 24, 22]
  
# Initiating the plot
plt.plot(x, y)
plt.title("PLOT")
  
# Setting the x and y labels
plt.xlabel("X-Axis")
plt.ylabel("Y-Axis")
  
# Setting the number of ticks
plt.xlim(0, 3)
plt.locator_params(axis='x', nbins=3)
  
# Showing the plot
plt.show()


Output:



How to Change the Number of Ticks in Matplotlib?

In this article, we will see how to change the number of ticks on the plots in matplotlib in Python.

Similar Reads

Method 1: Using xticks() and yticks()

xticks() and yticks() is the function that lets us customize the x ticks and y ticks by giving the values as a list, and we can also give labels for the ticks, matters, and as **kwargs we can apply text effects on the tick labels....

Method 2: Using locator_param()

...

Method 3: Using xlim()

...

Contact Us