Since NCL color tables are stored as RGB values, you can write a short function to read from NCL color table URL and retrieve the necessary data to rebuild the color table as a matplotlib colormap.
#python #colormap #matplotlib
import pandas as pd
import xarray as xr
from matplotlib.colors import LinearSegmentedColormap
NCL_COLOR_TABLES_URL = "https://www.ncl.ucar.edu/Document/Graphics/ColorTables/Files/"
def read_ncl_colortable(color_table_name: str) -> LinearSegmentedColormap:
"""
Read an NCL color table and return a matplotlib colormap.
"""
if not color_table_name.endswith(".rgb"):
color_table_name += ".rgb"
ncl_color_table_url = NCL_COLOR_TABLES_URL + color_table_name
df = pd.read_csv(
ncl_color_table_url, skiprows=6, header=None, sep="\s+", names=["r", "g", "b"]
)
df_scaled = df / 255.0
cmap = LinearSegmentedColormap.from_list(
color_table_name, df_scaled.to_numpy(), N=len(df_scaled)
)
return cmap
air = xr.tutorial.open_dataset("air_temperature")["air"]
cmap = read_ncl_colortable("sunshine_9lev")
air.isel(time=0).plot(x="lon", y="lat", cmap=cmap)
This is great!! Thanks Andrew!