How to change range of an colorbar in matplotlib?

48 Views Asked by At

I'm trying to create a plot of ocean surface nitrate (downloaded from NOAA). I'm having trouble adjusting the colorbar while keeping the other elements of the plot. I would like the colorbar to range from 0-8, with all values > 8 to be represented as the top end of the color spectrum.

import cartopy.crs as ccrs
import cartopy
from matplotlib import pyplot as plt
import cartopy.feature as cfeature
import numpy as np
import xarray as xr

nit = 'https://www.ncei.noaa.gov/thredds-ocean/dodsC/ncei/woa/nitrate/all/1.00/woa18_all_n00_01.nc'

nitr= xr.open_dataset(nit, decode_times=False)
nitr

variables = ['n_an']
nitr[variables]

nitr_5 = nitr.n_an.sel(depth=5,  method='nearest')
nitr_5

fig = plt.figure(figsize=(9,6))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
ax.gridlines()
nitr_5.plot(ax=ax, transform=ccrs.PlateCarree(), vmin=2, vmax=30, cbar_kwargs={'shrink': 0.4}, cbar)
ax.set_title("")

The above code should hopefully be reproducible-- when I try to do this using the .colorbar argument it gives me a separate, blank colorbar so I am looking for a solution that I will be able to implement with the dataset!

1

There are 1 best solutions below

1
adigitoleo On

The xarray package is controlling the colorbar via the cbar_kwargs dictionary, which is passed to matplotlib.figure.Figure.colorbar. By checking its documentation you can find the relevant arguments ticks and extend. Try using these cbar_kwargs:

cbar_kwargs={'shrink': 0.4, 'ticks': list(range(9)), 'extend': 'max'}