Open In App

Matplotlib.pyplot.xticks() in Python

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
5 Likes
Like
Report

matplotlib.pyplot.xticks() function is used to get or set the x-axis ticks in a plot. This function allows you to modify the labels and positions of the ticks along the x-axis, providing greater flexibility and control over your plots. Let's see an example to better understand this.

Example: Set Custom Tick Positions and Labels

Output:

xticksExample
Output

Explanation:

  • We can define specific tick positions and corresponding labels for the x-axis.
  • The x-axis will have ticks at positions 1, 3, and 5.
  • The labels will be "One", "Three", and "Five" corresponding to these positions.

Syntax

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

Parameters:

  • ticks: A list or array of positions where you want the ticks to appear on the x-axis. If not provided, it will return the current positions of the ticks.
  • labels: A list or array of labels corresponding to each tick position. These labels will be displayed at the tick positions. If not provided, the function will use the default numerical labels.
  • **kwargs: Additional keyword arguments, such as font size, color, rotation, etc., to customize the appearance of the ticks.

Return Value:

The function returns the current x-axis tick positions and labels.

Examples of Matplotlib.pyplot.xticks()

1. Customizing X-axis Tick Labels with Rotation and Adjusting Margins

Output:

Explanation: This code creates a plot with custom x-axis labels (Geeks1, Geeks2, etc.), rotates them vertically, and adjusts margins to avoid clipping of tick labels. plt.subplots_adjust() ensures the labels fit within the plot.

2. Using Matplotlib.pyplot.xticks() with Zoomed-In Inset Plot

Output:

Explanation: This code creates a main plot with a zoomed-in inset using zoomed_inset_axes. The get_demo_image() function loads a sample 15x15 data array, which is displayed in both the main plot and the inset. The inset plot zooms in on a specific portion of the main plot.


Next Article
Article Tags :
Practice Tags :

Similar Reads