mannaroth
mannaroth

Reputation: 1543

matplotlib axis labels not aligned with data bins

I am trying to plot a correlation matrix and instead of the bin number as a label (see the y-axis labels) I'd like to have the physical, actual units (the x-axis labels). Unfortunately I can't get to align the xticks with the center of the bins and I don't understand why I don't have a label at each column of the matrix.

"5.01" is the last bin label, not the second to last

The code below produces the figure:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
labels =['', '0.13','0.20','0.32','0.50','0.79','1.26','2.00','3.16','5.01']
plt.xticks(range(len(labels)+1), labels, size='small')
#The '+1 in range seems needed as if I don't include it the first label is not displayed at all
plt.imshow(np.corrcoef(bootstrap_samples_matrix.transpose()), interpolation='nearest', cmap=plt.cm.Reds, extent=(0.5,10.5,0.5,10.5), align="center")
plt.colorbar()

Upvotes: 2

Views: 2194

Answers (2)

mannaroth
mannaroth

Reputation: 1543

To align the xticks with the center of the bins and in order to have a label at each column of the matrix, one could do it by setting the labels manually.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

manual_labels =['0.20','0.32','0.50','0.79','1.26','2.00','3.16']
ax.set_xticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5])
ax.set_xticklabels(manual_labels, minor=False)

ax.set_yticks([0.5,1.5,2.5,3.5,4.5,5.5,6.5,7.5])
ax.set_yticklabels(manual_labels, minor=False)

Upvotes: 2

BubbleGuppies
BubbleGuppies

Reputation: 5920

You are setting the xticks to the location defined by your labels, but in reality they are not the same. I think you want to set the labels to the actual location, like so;

Replace: plt.xticks(range(len(labels)+1), labels, size='small')

With: ax.set_xticklabels(labels, minor=False)

Upvotes: 0

Related Questions