'Using the same colobar limits for all plots in pythons cartopy/matplotlib
I am trying to define upper and lower limits for both color-bar and the contour map using Pythons matplotlib and cartopy.
Context: I am plotting monthly average temperature data across an X (lat) and Y (lon) grid, via a 'FOR' loop for a total of 228 months. For each month the maximum and minimum temperature slightly varies. ie. some months may have a spatial temp range from 25 degcel to 28 degcel and in other months the spatial temp range may be from 26 to 32 degcel. Currently my code results in maps with color-bars and color contours that are independent of each other and hence not directly comparable.
What I want to achieve is that all cmaps produced from the loop follow the same colorbar and scale, i.e. from 25 degcel to 32 degcel.
Previously i would use 'clim' to define limits but that does not seem to work for this. Now what I am using is vmaxandvmin which partially works,i.e. it plots the map using the same scale but the colorbar is still independent. Any hints in the right direction are appreciated.
here is a sample of my code.
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from netCDF4 import Dataset
import matplotlib.pyplot as plt
import numpy as np
file = ('monthlyaverages.nc')
ds = Dataset(file, 'r')
ds.variables.keys()
lons = ds.variables['lon'][:]
lats=ds.variables['lat'][:]
time = ds.variables['time'][:]
sst = ds.variables['analysed_sst'][:]
for t in range(1,228):
plt.figure(figsize=(6,5))
ax1 = plt.subplot2grid((1,1), (0,0), colspan=1, projection=ccrs.PlateCarree(central_longitude=180))
ax1.coastlines(resolution='50m')
fill=ax1.contourf(lons, lats, sst[t,:,:].squeeze(), levels=10,
cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree(), vmax = 32, vmin = 25)
cb = plt.colorbar(fill, orientation='vertical', fraction=0.04, pad=0.04, location ='left')#
plt.title('Average SST for the month # '+ str(t))
plt.savefig('sst_'+ str(t)+'.tiff')```
thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
