Home > Enterprise >  Using 'set_x' to move xticklabel to right
Using 'set_x' to move xticklabel to right

Time:06-20

Here is an example plot along with a dataset.

fig, ax = plt.subplots(figsize = (5,5))
x_data = np.arange(0,5,1)
y_data = [10,20,4,1,28]
x_labels = ['Val1', 'Val2', 'A Lengthy', "Unexpected", 'Val5']
ax.bar(x_data, y_data, tick_label = x_labels)

enter image description here

I want to move the xticklabel Unexpected a little to the right. So I thought of using this

for val in ax.get_xticklabels():
    if val.get_text() == "Unexpected":
        x,y = val.get_position()
        print(f'Old Position [{x},{y}]')
        val.set_y(-0.03)
        val.set_x(x   0.25)
        x,y = val.get_position()
        print(f'New Position [{x},{y}]')

Here is the outcome

enter image description here

The label moves downwards but not towards the right.

I want to know why is set_x not working as expected. Is there anything overriding it? I got a enter image description here

CodePudding user response:

As in the enter image description here

However overriding internal functions seems dangerous and instead using transform as in @Redox's answer or here is better

  • Related