2

I am working on this plot: Current plot

Conceptually, would like to change x labels position from this: enter image description here

to this:

enter image description here

Is there a function for that? Do I need to manually change the position of my label and if so how?

I don't want to use :

plt.margins(x=0.04)

because it shifts my data as well, and I need, just 2006 shifted right and just 2018 shifted left.

DavidG
  • 24,279
  • 14
  • 89
  • 82
Charlotte
  • 89
  • 1
  • 11

2 Answers2

2

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:

enter image description here

DavidG
  • 24,279
  • 14
  • 89
  • 82
-1

You can use set_xlim() if you have just these 3 values.

X = [2006, 2012, 2018]
Y = [0, 15, 30]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X, Y, color='r')
ax.set_xlim(2005, 2019)
plt.xticks([2006, 2012, 2018])
plt.yticks([0, 30])
plt.show()
DavidG
  • 24,279
  • 14
  • 89
  • 82