5

I want to plot a correlation matrix with rotated labels. However, the labels are misplaced as seen below. I've tried to look at Matplotlib Python Barplot: Position of xtick labels have irregular spaces between eachother, but I can't make it work in my case as it builds on the layout of the bar diagram. The labels are added using the following code:

    fig  = plt.figure()  
    ax1  = fig.add_subplot(111)
    varLabels = ['n_contacts', 'n_calls', 'n_texts', 'dur_calls', 'morning', 'work-hours', 'evening', 'night', 'weekdays', 'friday', 'saturday', 'sunday']

    ax1.set_xticks(np.arange(0,12))
    ax1.set_yticks(np.arange(0,12))
    ax1.set_xticklabels(varLabels, rotation=45);
    ax1.set_yticklabels(varLabels, rotation=45);

enter image description here

Community
  • 1
  • 1
pir
  • 5,513
  • 12
  • 63
  • 101
  • They look fine to me. For each "tick" the centre of the word is aligned, as you'd expect it to be when you rotate (as you rotate about the centre of the word). – Ffisegydd Mar 23 '15 at 15:40
  • If the ticks were on both sides of the spine/axis, the connection might be clearer. – cphlewis Mar 23 '15 at 17:10

1 Answers1

8

By default matplotlib centers the tick labels at the tick positions. For 45° labels this can be confusing. However, you can edit the alignment properties to make the right aligned (and top aligned respectively).

...
ax1.tick_params(direction='inout')
ax1.set_xticklabels(varLabels, rotation=45, ha='right')
ax1.set_yticklabels(varLabels, rotation=45, va='top')
...

I'm not sure if the result is better / clearer though.

hitzg
  • 12,133
  • 52
  • 54
  • The new result is a bit clearer: http://imgur.com/vcMUfuW. However, it would be perfect if the center of the final letter in each label was aligned with the tick. The x-labels would have to be moved slightly to the right and the y-labels slightly upwards. – pir Mar 24 '15 at 08:21
  • Yes, you are right. To make it perfect you would need to shift the ticks (or the labels) slightly. To my knowledge matplotlib can't do that automatically, so you would have to shift them manually. One way of doing it is to use (invisible) minor ticks to position the labels. However, this is quite a bit of fine tuning. I usually use 90° labels with `ha='center'` exactly because of this – hitzg Mar 24 '15 at 08:46