Last active
September 5, 2024 08:21
-
-
Save lukegre/5618ede25a19a55346fc01ba8ef1fd98 to your computer and use it in GitHub Desktop.
Load IPCC cmaps (e.g., cmap="ipcc.prec_div"). A standalone script to load the IPCC continuous color maps listed in https://github.com/IPCC-WG1/colormaps/tree/master. Simply import this script to load the cmaps and access as cmap='ipcc.prec_div' for example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_github_filesystem(): | |
import fsspec | |
fs = fsspec.filesystem('github', org='IPCC-WG1', repo='colormaps') | |
return fs | |
def get_cmap(cmap_name, folder='continuous_colormaps_rgb_0-1'): | |
import numpy as np | |
fs = get_github_filesystem() | |
try: | |
cmap_file = fs.open(f'{folder}/{cmap_name}.txt') | |
except FileNotFoundError: | |
cmap_flist = get_continuous_cmap_flist(folder) | |
raise FileNotFoundError( | |
f'Colormap {cmap_name} not found in folder {folder}, ' | |
f'available colormaps are: {cmap_flist}') | |
rgb_data_in_the_txt_file = np.loadtxt(cmap_file) | |
# create the colormap | |
cmap_name = f'ipcc.{cmap_name}' | |
cmap = make_cmap_from_list(cmap_name, rgb_data_in_the_txt_file) | |
return cmap | |
def make_cmap_from_list(name, array): | |
import matplotlib.colors as mcolors | |
from matplotlib import pyplot as plt | |
cmap = mcolors.LinearSegmentedColormap.from_list(name, array) | |
# register this new colormap with matplotlib cm | |
try: | |
plt.register_cmap(name, cmap=cmap) | |
except ValueError: | |
pass | |
return cmap | |
def get_continuous_cmap_flist(folder): | |
fs = get_github_filesystem() | |
flist = fs.glob(f'{folder}/*.txt') | |
cmap_list = [f.split('/')[-1].split('.')[0] for f in flist] | |
return cmap_list | |
_git_folder = 'continuous_colormaps_rgb_0-1' | |
cmap_list = get_continuous_cmap_flist(_git_folder) | |
_cmap_dict = {name: get_cmap(name, folder=_git_folder) for name in cmap_list} | |
locals().update(_cmap_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment