Home > Back-end >  Matplotlib x-axis label re-positioning
Matplotlib x-axis label re-positioning

Time:09-02

I am trying to move the x-axis label "number of patients" right below the x-tick value '0' (please refer to the image). Please kindly advise on this matter. image

The code I used to create the bar chart is as follows:

n_counts.plot.barh(stacked=True, width=0.7, figsize=(12,8), color=['navy','cornflowerblue']);

plt.draw()

# Get current tick positions and labels
pos, lab = plt.xticks()

# Edit labels
new_label = [int(x)*-1 if int(x)<0 else int(x) for x in pos]

# Set new labels
plt.xticks(pos, new_label)
plt.ylabel('neighbourhood', fontsize=13)
plt.xlabel('number of patients', fontsize=13)
plt.legend(['attended', 'not attended'], title='Attendance')
plt.title('            Attendance Counts in Top 20 Regions', loc='left', fontsize=16);

CodePudding user response:

You need to transform the data coordinate of the x-label (0 in the example) to axes coordinates to place the label:

import matplotlib.pyplot as plt
import matplotlib as mpl

fig, ax = plt.subplots()

ax.set_xlim((-2, 10))
x = 0  # position of xlabel

ax.set_xlabel("xlabel", ha='left', x=ax.transAxes.inverted().transform(ax.transData.transform((x, 0)))[0])

enter image description here

transData transforms data coordinates into display coordinates that are then transformed back into Axes coordinates using the inverse transAxes Axes transformation. See the enter image description here

  • Related