How to Create a Color Bar for Multiple Subplots in Python

Published: 10 July 2022
on channel: PikFix
3,768
43

In this lesson we'll take a look on how to create a united color bar for multiple subplots or a color bar per each subplot.
The code that is used is as follows-


import matplotlib.pyplot as plt
import matplotlib.cm as cm
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import pandas as pd
def main():
df = pd.read_csv(r'C:\Users\karin\Desktop\Work\PikFix\Data WWLN\Feb2022\united.txt', delimiter=',',
names=['Date', 'Time', 'Lat', 'Long', 'Resid', 'Nsta'])
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(23, 9), subplot_kw={'projection': ccrs.PlateCarree()})
extent = [-5.5, 37, 28, 46]
cmap = cm.get_cmap('YlOrRd')
norm = cm.colors.LogNorm(vmin= 1, vmax= 1000)

for row in axes:
ax1 = row[0]
ax2 = row[1]
ax1.add_feature(cfeature.LAND, color='white', zorder=50)
ax1.add_feature(cfeature.COASTLINE, color='k', zorder=50)
ax2.add_feature(cfeature.LAND, color='white', zorder=50)
ax2.add_feature(cfeature.COASTLINE, color='k', zorder=50)
ax1.set_extent(extent)
ax2.set_extent(extent)

ax0 = axes[0][0]
ax1 = axes[0][1]
ax2 = axes[1][0]
ax3 = axes[1][1]

hist1 = ax0.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= cm.colors.LogNorm(vmin= 1, vmax= 10))
hist2 = ax1.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= cm.colors.LogNorm(vmin= 1, vmax= 100))
hist3 = ax2.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= cm.colors.LogNorm(vmin= 1, vmax= 1000))
hist4 = ax3.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= cm.colors.LogNorm(vmin= 1, vmax= 10000))

hist1 = ax0.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= norm)
hist2 = ax1.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= norm)
hist3 = ax2.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= norm)
hist4 = ax3.hist2d(df.Long, df.Lat, range=[(-5.5, 37), (30, 46)], bins=(500, 200), cmap= cmap, norm= norm)
fig.tight_layout()

cbar = fig.colorbar(hist1[3], ax=axes)
cbar1 = fig.colorbar(hist1[3], ax=ax0)
cbar2 = fig.colorbar(hist2[3], ax=ax1)
cbar3 = fig.colorbar(hist3[3], ax=ax2)
cbar4 = fig.colorbar(hist4[3], ax=ax3)

vmin, vmax = hist1[-1].get_clim()
print('\n', vmin, vmax, '\n')
if _name_ == '__main__':
main()


Watch video How to Create a Color Bar for Multiple Subplots in Python online without registration, duration hours minute second in high quality. This video was added by user PikFix 10 July 2022, don't forget to share it with your friends and acquaintances, it has been viewed on our site 3,768 once and liked it 43 people.