Loading [MathJax]/extensions/tex2jax.js

Friday, October 21, 2011

Colorbar titles in matplotlib

In matplotlib sometimes you want to put some title in a colorbar, when producing a filled contour plot or similar. One way is to simply:
fig=plt.figure()
## AXES HANDLE
ax=fig.add_axes(mpltr.Bbox([[ .14 , .14 ],[ .90 , .92 ]]))
## COLORBAR AXES HANDLE
cx=fig.add_axes(mpltr.Bbox([[ .91 , .14 ],[ .93 , .92 ]]))
...
## PLOT THE STUFF YOU WANT
ax.contourf(X, Y, Z, etc... )
...
## COLORBAR
cb=plt.colorbar(cf, cax=cx)
plt.figtext(.91, .92, (r"Variable Z"), va='bottom', ha='left')
...

Another way is to use the set_title or the set_xlabel of your colorbar axes. For the first:
...
## COLORBAR
cb=plt.colorbar(cf, cax=cx)
cx.set_title(r"Variable Z")
...

However in this way I don't know how to set the title at a distance from the axes. For the second, this can be done using the labelpad:
...
## COLORBAR
cb=plt.colorbar(cf, cax=cx)
cx.set_xlabel(r"Variable Z", labelpad=10)
cx.xaxis.set_label_position('top')
...

No comments:

Post a Comment