33
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