I'm just trying to set different rotations for the x axis tick labels of a pyplot figure.
Lets take this exemple :
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(0,5)
y=np.arange(0,5)
plt.xlim(0,4)
plt.ylim(0,4)
plt.plot(x,y)
plt.plot((1,1),(0,4),color='red',lw=1)
plt.plot((2,2),(0,4),color='red',lw=1)
plt.plot((2.98,2.98),(0,4),color='red',lw=1)
plt.plot((3,3),(0,4),color='red',lw=1)
lab_ticks=['Label 1','Label 2','Label 3','Label 4']
x_ticks=[1,2,2.98,3]
plt.xticks(x_ticks,lab_ticks,rotation=90)
plt.savefig('im1.png')
plt.show()
This code give us the following figure :

My problem isn't that entire labels are not shown, I know how to fix it. My problem is that Label 3 and Label 4 are too much nearby and they overlap each other.
I want to set the rotation of Label 3 at 45 and the others at 90, but when I tried to separate my lab_ticks and x_ticks, only the last plt.xticks() is shown :
lab_ticks=['Label 1','Label 2','Label 4']
x_ticks=[1,2,3]
lab_ticks2=['Label 3']
x_ticks2=[2.98]
plt.xticks(x_ticks,lab_ticks,rotation=90)
plt.xticks(x_ticks2,lab_ticks2,rotation=45,ha='right')

Does anyone has a trick to fix that problem ?
Thanks in advance !
Smich
You can set the rotation individually for each ticklabel. To this end you need to get the ticklabels ax.get_xticklabels() and apply a rotation to each one via .set_rotation(angle).
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([1,2,3,4],[1,2,1,2])
labels=["Label {}".format(i+1) for i in range(4)]
ax.set_xticks(range(1,5))
ax.set_xticklabels(labels)
for i, t in enumerate(ax.get_xticklabels()):
t.set_rotation(i*45)
plt.show()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With