You do this by digging slightly deeper into the workings of matplotlib ticks using the object oriented API.
First off, you can get a list of your major ticks using xaxis.get_major_ticks()
. This returns a list of matplotlib.axis.XTick
objects. These have an attribute label1
which is the label of the tick. This is a Text instance which has a property set_horizontalalignment(align)
. Which states:
set_horizontalalignment(align)
Set the horizontal alignment to one of
ACCEPTS: [ ‘center’ | ‘right’ | ‘left’ ]
Then, as you only want to modify the first and last ticks, simply set the alignment of the specific ticks using the first and last entries in the list.
A working example:
import matplotlib.pyplot as plt
x = [1,2,3]
y = [4,5,6]
labels = ["2004", "2006", "2008"]
fig, ax = plt.subplots()
ax.margins(0)
ax.plot(x,y)
ax.set_xticks(x)
ax.set_xticklabels(labels)
# above code recreates the issue
# get list of x tick objects
xTick_objects = ax.xaxis.get_major_ticks()
xTick_objects[0].label1.set_horizontalalignment('left') # left align first tick
xTick_objects[-1].label1.set_horizontalalignment('right') # right align last tick
plt.show()
Which gives:
