How to Create a Color Bar for Multiple Subplots in Python

Опубликовано: 10 Июль 2022
на канале: 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()


Смотрите видео How to Create a Color Bar for Multiple Subplots in Python онлайн без регистрации, длительностью часов минут секунд в хорошем качестве. Это видео добавил пользователь PikFix 10 Июль 2022, не забудьте поделиться им ссылкой с друзьями и знакомыми, на нашем сайте его посмотрели 3,768 раз и оно понравилось 43 людям.