Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotated axis labels are placed incorrectly (matplotlib)

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

like image 1000
pir Avatar asked Mar 23 '15 15:03

pir


1 Answers

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.

like image 56
hitzg Avatar answered Oct 12 '22 13:10

hitzg