Reputation: 6014
I am trying to place a label on top of a colorbar. Drawing the label works fine, but the final position adjustment of the colorbar axis is not working. It seems like the call to "set_position" simply does nothing. Here is my code:
import numpy as np
import matplotlib.pyplot as plt
# Plot some sample data.
X, Y = np.meshgrid(np.arange(1, 10, 0.1), np.arange(1, 10, 0.1))
Z = np.sin(X) ** 2 + np.cos(Y) ** 2
plt.pcolor(X, Y, Z)
# Add the colorbar.
cb = plt.colorbar(shrink=0.8)
cax = cb.ax
# Add label on top of colorbar.
cb.ax.set_xlabel("mylabel")
cb.ax.xaxis.set_label_position('top')
cb.ax.xaxis.set_label_coords(1.8, 1.05)
# Adjust colorbar position (NOT working).
pos1 = cax.get_position()
yshift = pos1.height * 0.05 / 0.8
pos2 = [pos1.x0, pos1.y0 - yshift, pos1.width, pos1.height]
cax.set_position(pos2)
# Adjust and show the plot.
plt.tight_layout()
plt.show()
What am i doing wrong?
Upvotes: 3
Views: 3609
Reputation: 339062
Two things:
yshift
you use is rather small, so an effect my not be directly obvious.plt.tight_layout()
rearranges the axes, and thus overwrites the position you have set.So you would probably want to first call plt.tight_layout()
and afterwards change the position.
Upvotes: 1