15.1 C
London
Friday, July 5, 2024
HomePythonMatplotlib in PythonHow to Set X-Axis Values in Matplotlib

How to Set X-Axis Values in Matplotlib

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to set the x-axis values for a plot in Matplotlib:

#specify x-axis locations
x_ticks = [2, 4, 6, 8, 10]

#specify x-axis labels
x_labels = ['A', 'B', 'C', 'D', 'E'] 

#add x-axis values to plot
plt.xticks(ticks=x_ticks, labels=x_labels)

The following examples show how to use this syntax in practice.

Example 1: Set X-Axis Values at Equal Intervals

The following code shows how to set the x-axis values at equal intervals in Matplotlib:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify x-axis locations
x_ticks = [2, 4, 6, 8, 10]

#specify x-axis labels
x_labels = ['A', 'B', 'C', 'D', 'E'] 

#add x-axis values to plot
plt.xticks(ticks=x_ticks, labels=x_labels)

Notice that each x-axis value appears at equally spaced intervals.

Example 2: Set X-Axis Values at Unequal Intervals

The following code shows how to set the x-axis values at unequal intervals in Matplotlib:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify x-axis locations
x_ticks = [1, 2, 6, 10]

#specify x-axis labels
x_labels = [1, 2, 6, 10] 

#add x-axis values to plot
plt.xticks(ticks=x_ticks, labels=x_labels)

Example 3: Set X-Axis Values at Data Points Only

The following code shows how to set the x-axis values at the data points only:

import matplotlib.pyplot as plt

#define x and y
x = [1, 4, 10]
y = [5, 11, 27]

#create plot of x and y
plt.plot(x, y)

#specify x-axis labels
x_labels = ['A', 'B', 'C'] 

#add x-axis values to plot
plt.xticks(ticks=x, labels=x_labels)

Note: You can find the complete documentation for the plt.xticks() function here.

Additional Resources

How to Set Axis Ranges in Matplotlib
How to Set Tick Labels Font Size in Matplotlib
How to Create Multiple Matplotlib Plots in One Figure

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories