In matplotlib, how do I move the y tick labels to the far left side of the charting areas when I have moved the left spine?
Code:
import matplotlib.p
Changing the transformation of the y-ticklabels back to the original y-axis transform would give you the desired ticks on the left side of the axes.
plt.setp(ax.get_yticklabels(), transform=ax.get_yaxis_transform())
Complete code for reproducibility
import matplotlib.pyplot as plt
X = range(-10,5)
y = [i**2 for i in X]
fig, ax = plt.subplots(1,1, figsize=(10,8))
plt.plot(X, y)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_position('zero')
plt.setp(ax.get_yticklabels(), transform=ax.get_yaxis_transform())
plt.show()
You can exploit the set_position
attribute of your tick labels by iterating over them. Here you have to pass the (xy) value to be set as the new location of your tickl-labels. We know the x-position is -10. What I found is that it does not matter what y-position you specify, the ticks are offset by the value of x
which kind of makes sense too because the tick labels have to correspond to the ticks on the y-axis. However, one can't leave the y-value empty. So specifying (-10)
won't work and (-10, 0)
, (-10, -100)
or (-10, 1000)
have no effect on the y-position of the ticks. The reason is as
@ImportanceOfBeingErnest clarified: The y position of the label will be determined by the y-values of your data and is set at draw time after applying the changes.
for tick in ax.yaxis.get_major_ticks():
print (tick.label.set_position((-10, 0)))