The ususal way to add a colorbar is by simply putting it next to the axes:
fig.colorbar(sm)
where fig
is the figure and sm
is the scalar mappable to which the colormap refers. In the case of the bars, you need to create this ScalarMappable
yourself. Apart from that there is no need for complex creation of multiple axes.
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
fig , ax = plt.subplots()
x = [0,1,2,3]
y = np.array([34,40,38,50])*1e3
norm = matplotlib.colors.Normalize(30e3, 60e3)
ax.bar(x,y, color=plt.cm.plasma_r(norm(y)) )
ax.axhline(4.2e4, color="gray")
ax.text(0.02, 4.2e4, "42000", va='center', ha="left", bbox=dict(facecolor="w",alpha=1),
transform=ax.get_yaxis_transform())
sm = plt.cm.ScalarMappable(cmap=plt.cm.plasma_r, norm=norm)
sm.set_array([])
fig.colorbar(sm)
plt.show()

If you do want to create a special axes for the colorbar yourself, the easiest method would be to set the width already inside the call to subplots
:
fig , (ax, cax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios" : [10,1]})
and later put the colorbar to the cax
axes,
fig.colorbar(sm, cax=cax)
Note that the following questions have been asked for this homework assignment already: