Home » Python » plot with custom text for x axis points

plot with custom text for x axis points

Posted by: admin November 29, 2017 Leave a comment


I am drawing a plot using matplotlib and python like the sample code below.

x = array([0,1,2,3])
y = array([20,21,22,23])

As it is the code above on the x axis I will see drawn values 0.0, 0.5, 1.0, 1.5 i.e. the same values of my reference x values.

Is there anyway to map each point of x to a different string? So for example I want x axis to show months names( strings Jun, July,...) or other strings like people names ( "John", "Arnold", ... ) or clock time ( "12:20", "12:21", "12:22", .. ).

Do you know what I can do or what function to have a look at?
For my purpose could it be matplotlib.ticker of help?


You can manually set xticks (and yticks) using pylab.xticks:

import matplotlib.pyplot as plt
import numpy as np

x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)


The answer from @unutbu works perfectly for the pyplot – MATLAB style plotting.

However, for the object oriented API of matplotlib one can plot custom text on the x-ticks of an axis with following code:

x = np.arange(2,10,2)
y = x.copy()
x_ticks_labels = ['jan','feb','mar','apr','may']

fig, ax = plt.subplots(1,1) 

# Set number of ticks for x-axis
# Set ticks labels for x-axis
ax.set_xticklabels(x_ticks_labels, rotation='vertical', fontsize=18)

enter image description here