Matplotlib xticks() in Python With Examples

In this article, we will discuss the Matplotlib xticks() in Python. Matplotlib library in Python is a numerical – mathematical extension for NumPy library. The Pyplot function of this Matplotlib module provides a MATLAB-like interface. The matplotlib.pyplot.xticks() function is used to get or set the current tick locations and labels of the x-axis. It passes no arguments to return the current values without modifying them. Before we look into various implementations of Matplotlib xticks(), let me brief you with the syntax and return the same.

Syntax of Matplotlib xticks()

matplotlib.pyplot.xticks(ticks=None, labels=None, \*\*kwargs)

Parameters:

  • ticks: array-like containing the list of xtick locations. Passing an empty list removes all xticks. (Optional)
  • labels: array-like containing the labels to place at the given ticks locations. This argument can only be passed if ticks are passed as well. (Optional)
  • **kwargs: text properties that can be used to control the appearance of the labels.

Return Type

The Matplotlib xticks() function returns:
locs: The list of xtick locations.
labels: The list of xlabel text objects.

Example of Matplotlib xticks() in Python

import matplotlib.pyplot as plt
import numpy as np
import math
x = np.arange(0, math.pi*2, 0.05)
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
y = np.sin(x)
ax.plot(x, y)
ax.set_xlabel(‘angle’)
ax.set_title('sine')
ax.set_yticks([-1,0,1])
ax.set_xticks([0,2,4,6])
ax.set_xticklabels(['zero','two','four','six'])
plt.show()

Output:

Example of Matplotlib xticks() in Python

Explanation:

In the above example, an array is defined containing the xticks locations, i.e., [0, 2, 4, 6]. And that array is passed as argument to the ax.set_xticks() function. Another array is defined containing the labels to place at the tick locations i.e., [‘zero’, ‘two’, ‘four’, ‘six’]. This array is then passed as an argument to the ax.set_xticklabels() function. Thus these two matplotlib xticks() functions as a list of xtick locations and a list of xlabel text objects.

Matplotlib xticks() Spacing

import matplotlib.pyplot as plt

N = 100
data = plt.np.linspace(0, N, N)

plt.plot(data)

plt.xticks(range(N)) # add loads of ticks
plt.grid()
plt.tight_layout()
plt.show()

Output:

Matplotlib xticks() Spacing

Explanation:

Firstly, in the above example, the ‘N’ is 100 and range(N) is an argument to the plt.xticks(). As a result, the output is a list of xticks locations, and labels with very little space between them or overlapped. Thus to adjust the constant spacing, the xticks label the figure size increased by the figsize() function. Or you have to set the tick_spacing to a constant value as desired.

Axis level xticks frequency

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(12, 6))

ax = fig.add_subplot(122)

y = np.random.randint(low=0, high=50, size=100)
z = np.random.randint(low=0, high=50, size=100)

ax.plot(y, color='black')
ax.plot(z, color='green')

ax.set_xticks(np.arange(0, len(x)+1, 25))
ax.set_yticks(np.arange(0, max(y), 25))

plt.show()

Output:

Setting xticks() frequency

Explanation:

Firstly, in the above example, the xticks frequency is as per our choice. And to do so, ‘np.arange(0, len(x)+1, 25)’ is an argument to the ax.set_xticks() function. This sets the frequency of of xticks labels to 25 i.e., the labels appear as 0, 25, 50, etc. Thus returning a list of xticks labels along the x-axis appearing at an interval of 25.

Rotation of Matplotlib xticks() in Python

from matplotlib import pyplot as plt
from datetime import datetime, timedelta

values = range(10)
dates = [datetime.now()-timedelta(days=_) for _ in range(10)]

fig,ax = plt.subplots()
plt.plot(dates, values)
plt.xticks(rotation=45)
plt.grid(True)

plt.show()

Output:

Rotation of Matplotlib xticks() in Python

Explanation:

In the above example, a ‘date’ array is defined containing the list of dates, which are the xticks labels for the plot. The plt.xticks() gets or sets the properties of tick locations and labels of the x-axis. ‘Rotation = 45’ is passed as an argument to the plt.xticks() function. Rotation is the counter-clockwise rotation angle of x-axis label text. As a result, the output is given as the xticks labels rotated by an angle o 45 degrees.

Matplotlib xticks Angle

We can rotate the angle of the x axis label with the help of xticks function. 

Its syntax is:

plt.xticks(rotation = n)

Here, n means the number by which you want to rotate. It can be 25,50, etc.

Matplotlib xticks Bold

To make xticks bold, use fontweight as bold. For example, 

Myplt.xticks(fontweight='bold')

This will make the xticks bold.

Matplotlib xticks Color

We use xticks() function to alter the colour of xticks on your plot.

plt.xticks(color='green')

We can use any colour of our choice.

How to set xticks every 10 difference?

You can set your own range using the arange function of numpy library.  It supports float values too. Your frequency will change with this. 

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

FAQs

How to use set xticks in matplotlib?

This sets the data points in matplotlib. 
ax.set_xticks([2,4,6])
These data points will be marked on the plot now.

What is the use of Xticks () and Yticks () in plotting?

The xticks() and yticks() specify where the data points will be marked on plot.

Must Read

Matplotlib pcolormesh in Python with Examples
Matplotlib tight_layout in Python with Examples
How to Clear Plot in Matplotlib Using clear() Method

Conclusion

In this article, we discussed various ways of implementing Matplotlib xticks() in Python programs. We learned how to set xticks labels frequency and spacing between them. And also how to rotate the xticks labels through the desired measure. We can also keep the xticks off by not passing any argument to the matplotlib xticks() function. Refer to this article for any queries related to the xticks() function.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

 

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments