How to Use Matplotlib set_xticks?

While working with data visualization libraries, Matplotlib has always been my go-to tool for creating clear and informative charts. One common task I frequently encounter is customizing the x-axis ticks to better represent data, especially when dealing with dates, categories, or specific intervals.

Matplotlib’s set_xticks method is an easy yet useful way to control where and how the ticks appear on the x-axis. In this tutorial, I will share practical methods to use set_xticks effectively, along with examples that you can apply directly to your projects.

What is Matplotlib’s set_xticks?

In simple terms, set_xticks is a method available on Matplotlib’s Axes object that allows you to specify the exact locations of ticks on the x-axis.

By default, Matplotlib automatically places ticks based on the data range, but sometimes this default behavior doesn’t fit your needs. For example, if you want to show ticks only on specific months or certain numeric values, set_xticks gives you full control.

Read Matplotlib Not Showing Plot

How to Use set_xticks: Basic Example

Let me start with a basic example. Suppose you have monthly sales data for a company based in New York, and you want to plot this data with ticks only on the first day of each quarter.

import matplotlib.pyplot as plt

# Sample sales data for 12 months
months = range(1, 13)
sales = [200, 220, 250, 270, 300, 320, 310, 330, 360, 380, 400, 420]

fig, ax = plt.subplots()
ax.plot(months, sales)

# Set x-axis ticks to the first month of each quarter
quarter_ticks = [1, 4, 7, 10]
ax.set_xticks(quarter_ticks)

# Optional: set labels for these ticks
ax.set_xticklabels(['Jan', 'Apr', 'Jul', 'Oct'])

plt.title('Quarterly Sales in New York')
plt.xlabel('Month')
plt.ylabel('Sales (in thousands)')
plt.show()

I executed the above example code and added the screenshot below.

set_xticks

Here, set_xticks is used to place ticks only at months 1, 4, 7, and 10, representing the start of each quarter. This makes the chart cleaner and easier to read.

Read Matplotlib Multiple Plots

Method 1: Use set_xticks with Numeric Values

This is the easy way to use set_xticks, you provide a list of numeric positions where you want the ticks.

For example, if you are plotting daily temperatures over 30 days and want ticks every 5 days:

days = range(1, 31)
temperatures = [70, 72, 68, 65, 74, 75, 73, 70, 69, 72, 74, 76, 77, 75, 74,
                73, 72, 70, 68, 67, 69, 71, 72, 74, 75, 77, 78, 76, 75, 74]

fig, ax = plt.subplots()
ax.plot(days, temperatures)

# Set ticks every 5 days
tick_positions = list(range(1, 31, 5))
ax.set_xticks(tick_positions)

plt.title('Daily Temperatures in Chicago - July')
plt.xlabel('Day')
plt.ylabel('Temperature (°F)')
plt.show()

I executed the above example code and added the screenshot below.

ax.set_xticks

This method works perfectly when your x-axis is numeric or integer-based.

Check out Matplotlib Legend Font Size

Method 2: Use set_xticks with Date or Time Data

When working with dates, such as plotting monthly unemployment rates across the USA, you often want to set ticks at specific dates.

Matplotlib’s set_xticks can accept date values if you convert them properly using matplotlib.dates.

Here’s how I handle it:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime

# Dates for each month in 2023
dates = [datetime.datetime(2023, month, 1) for month in range(1, 13)]
unemployment_rate = [4.1, 4.0, 3.9, 4.2, 4.3, 4.1, 3.8, 3.7, 3.9, 4.0, 4.1, 4.2]

fig, ax = plt.subplots()
ax.plot(dates, unemployment_rate)

# Set ticks on the first day of each quarter
quarter_dates = [datetime.datetime(2023, month, 1) for month in [1, 4, 7, 10]]
ax.set_xticks(quarter_dates)

# Format tick labels as month names
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))

plt.title('Quarterly Unemployment Rate in the USA (2023)')
plt.xlabel('Month')
plt.ylabel('Unemployment Rate (%)')
plt.show()

I executed the above example code and added the screenshot below.

plt.set_xticks

By passing datetime objects to set_xticks, you gain precise control over tick placement on time series plots.

Method 3: Combine set_xticks with set_xticklabels

Sometimes, you want to set ticks at specific positions but display more meaningful custom labels.

For example, if you plot sales data for US states and want to show abbreviated state names on the x-axis:

states = ['California', 'Texas', 'New York', 'Florida', 'Illinois']
sales = [500, 450, 400, 350, 300]

fig, ax = plt.subplots()
ax.bar(range(len(states)), sales)

# Set ticks at bar centers
ax.set_xticks(range(len(states)))

# Custom labels - state abbreviations
state_abbr = ['CA', 'TX', 'NY', 'FL', 'IL']
ax.set_xticklabels(state_abbr)

plt.title('Sales by State - Q1 2023')
plt.xlabel('State')
plt.ylabel('Sales (in millions)')
plt.show()

This approach is especially useful when your x-axis data is categorical.

Tips for Using set_xticks Effectively

  • Avoid Overcrowding: Don’t set too many ticks; it makes the chart cluttered. Pick meaningful intervals like quarters, months, or every 5 units.
  • Use with set_xticklabels: Always pair set_xticks with set_xticklabels if you want to customize the labels to something more readable.
  • Datetime Handling: When working with dates, use matplotlib.dates for formatting and tick placement.
  • Remember the Axis Object: set_xticks is a method on the Axes object, so if you’re using plt.plot(), get the current axes with ax = plt.gca() before setting ticks.

Using set_xticks has saved me countless hours when I needed to make my plots clearer and more professional. Whether you’re preparing reports for a marketing team in San Francisco or analyzing financial data for Wall Street, controlling your x-axis ticks can make a huge difference in how your data story is perceived.

I encourage you to experiment with these methods and tailor your tick marks to your audience’s needs.

Other Python articles you might like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.