Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use new colormap registry in matplotlib #413

Merged
merged 2 commits into from
Feb 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions typhon/plots/cm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@

.. _cmocean: http://matplotlib.org/cmocean/
"""
from matplotlib.colors import (LinearSegmentedColormap, ListedColormap)
from matplotlib.cm import register_cmap
import matplotlib as mpl

from ._cmocean import datad as _cmocean_datad
from ._cm import datad as _cm_datad
Expand All @@ -33,16 +32,16 @@ def _rev_cdict(cdict):
cmaps = {}
for (name, data) in datad.items():
if isinstance(data, dict):
cmaps[name] = LinearSegmentedColormap(name, data)
cmaps[name + '_r'] = LinearSegmentedColormap(
cmaps[name] = mpl.colors.LinearSegmentedColormap(name, data)
cmaps[name + '_r'] = mpl.colorsLinearSegmentedColormap(
name + '_r', _rev_cdict(data))
elif isinstance(data, list):
cmaps[name] = ListedColormap(data, name)
cmaps[name + '_r'] = ListedColormap(data[::-1], name + '_r')
cmaps[name] = mpl.colors.ListedColormap(data, name)
cmaps[name + '_r'] = mpl.colors.ListedColormap(data[::-1], name + '_r')

locals().update(cmaps)

for name, cm in cmaps.items():
register_cmap(name, cm)
mpl.colormaps.register(cmap=cm, name=name)

__all__ = list(cmaps.keys())
31 changes: 15 additions & 16 deletions typhon/plots/colors/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
from functools import lru_cache
from warnings import warn

import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.colors import LinearSegmentedColormap
import numpy as np

from typhon.utils import deprecated
Expand Down Expand Up @@ -57,9 +56,9 @@ def cmap2rgba(cmap=None, N=None, interpolate=True):

nlut = N if interpolate else None

if interpolate and isinstance(cmap, colors.ListedColormap):
if interpolate and isinstance(cmap, mpl.colors.ListedColormap):
# `ListedColormap` does not support lookup table interpolation.
cmap = colors.LinearSegmentedColormap.from_list('', cmap.colors)
cmap = mpl.colors.LinearSegmentedColormap.from_list('', cmap.colors)
return cmap(np.linspace(0, 1, N))

return plt.get_cmap(cmap.name, lut=nlut)(np.linspace(0, 1, N))
Expand All @@ -71,7 +70,7 @@ def _to_hex(c):

# Convert rgb to hex.
if ctype is tuple or ctype is np.ndarray or ctype is list:
return colors.rgb2hex(c)
return mpl.colors.rgb2hex(c)

if ctype is str:
# If color is already hex, simply return it.
Expand All @@ -80,7 +79,7 @@ def _to_hex(c):
return c

# Convert named color to hex.
return colors.cnames[c]
return mpl.colors.cnames[c]

raise Exception("Can't handle color of type: {}".format(ctype))

Expand All @@ -102,8 +101,8 @@ def colors2cmap(*args, name=None):
raise Exception("Give at least two colors.")

cmap_data = [_to_hex(c) for c in args]
cmap = colors.LinearSegmentedColormap.from_list(name, cmap_data)
plt.register_cmap(name, cmap)
cmap = mpl.colors.LinearSegmentedColormap.from_list(name, cmap_data)
mpl.colormaps.register(cmap=cmap, name=name)

return cmap

Expand Down Expand Up @@ -289,13 +288,13 @@ def cmap_from_act(file, name=None):
colors = rgb[:ncolors*3].reshape(ncolors, 3) / 255

# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, colors, N=ncolors)
plt.register_cmap(cmap=cmap) # Register colormap.
cmap = mpl.colors.LinearSegmentedColormap.from_list(name, colors, N=ncolors)
mpl.colormaps.register(cmap=cmap) # Register colormap.

# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
cmap_r = mpl.colors.LinearSegmentedColormap.from_list(
name + '_r', np.flipud(colors), N=ncolors)
plt.register_cmap(cmap=cmap_r)
mpl.colormaps.register(cmap=cmap_r)

return cmap

Expand Down Expand Up @@ -329,13 +328,13 @@ def cmap_from_txt(file, name=None, N=-1, comments='%'):
raise Exception('RGB value out of range: [0, 1].')

# Create and register colormap...
cmap = LinearSegmentedColormap.from_list(name, rgb, N=N)
plt.register_cmap(cmap=cmap)
cmap = mpl.colors.LinearSegmentedColormap.from_list(name, rgb, N=N)
mpl.colormaps.register(cmap=cmap)

# ... and the reversed colormap.
cmap_r = LinearSegmentedColormap.from_list(
cmap_r = mpl.colors.LinearSegmentedColormap.from_list(
name + '_r', np.flipud(rgb), N=N)
plt.register_cmap(cmap=cmap_r)
mpl.colormaps.register(cmap=cmap_r)

return cmap

Expand Down
9 changes: 9 additions & 0 deletions typhon/tests/plots/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ def teardown_method(self):
"""Delete temporary file."""
os.remove(self.f)

def test_colors2cmap(self):
"""Check colors to colormap conversion."""
color_list = ["#0000ff", "#ff0000"]

cmap = colors.colors2cmap(*color_list, name="test_colors2cmap")

assert mcolors.rgb2hex(cmap(0.0)) == color_list[0]
assert mcolors.rgb2hex(cmap(1.0)) == color_list[-1]

def test_cmap2rgba(self):
"""Check colormap to RGB conversion."""
ref = np.loadtxt(os.path.join(self.ref_dir, 'viridis.txt'),
Expand Down