Why does the title show above the colorbar but below the map?

49 Views Asked by At

Please see the codes below:

plt.figure(figsize=(10,5))
m = Basemap(projection='cyl', resolution='c', llcrnrlat=0, urcrnrlat=90, llcrnrlon=0, urcrnrlon=360)
x, y = m(lon, lat)
scatter = m.scatter(x, y, c=theta, cmap='rainbow', norm=Normalize(vmin=math.floor(np.min(theta)/10.0)*10.0, vmax=math.ceil(np.max(theta)/10.0)*10.0), marker='o', s=20, edgecolors='none')

m.drawparallels(np.arange(0, 91, 20), labels=[1,0,0,0], linewidth=0.4)
m.drawmeridians(np.arange(0, 361, 40), labels=[0,0,0,1], linewidth=0.4)

x_special, y_special = m(lon[0], lat[0])
m.scatter(x_special, y_special, marker='*', s=50, edgecolors='black', linewidths=1.5)
x_special, y_special = m(lon[mintind], lat[mintind])
m.scatter(x_special, y_special, marker='^', s=40, c='blue')

m.drawcoastlines(linewidth=0.4)
#m.drawcountries(linewidth=0.2)
m.drawmapboundary(fill_color='white')

cax = plt.axes([0.1, 0.1, 0.65, 0.02])  # Define position and size of colorbar
cbar = plt.colorbar(scatter, cax=cax, orientation='horizontal')
cbar.set_label('Theta')
plt.title(date.strftime('%y%m%d%H'), fontsize=12)
#--------------------------------------------------------------------------------
save_path = os.path.join('/', *trajfile.split('/')[:-1], 'fig_' + date.strftime('%y%m%d%H') + '.png')
plt.savefig(save_path, bbox_inches='tight', dpi=300)
plt.close()

In the output figures (for reference, see the bottom), my title show only above the colorbar, but below the map. Why is it?

enter image description here

Actually I don't understand the logic of plotting in python. Like, I don't know why the handle 'm' is not explicitly used in the plot, but still it can be plot.

1

There are 1 best solutions below

1
tmdavison On

plt.title will add a title to the last active matplotlib.Axes instance. In this case, you create an Axes instance for the colorbar (cax), then add the title, so the title gets added to that Axes instance.

One option would be to move plt.title above the creation of the colorbar, e.g. put it after m.drawmapboundary() in your code.

Another option would be to explicitly add the title to the Axes that the Basemap instance (m) is being drawn on. Something like:

m.ax.set_title(date.strftime('%y%m%d%H'), fontsize=12)

should work here.