Skip to content

Commit

Permalink
Merge pull request #3186 from CarlAndersson/get-colorscale-by-name
Browse files Browse the repository at this point in the history
Implements getting a colorscale by name
  • Loading branch information
nicolaskruchten authored May 7, 2021
2 parents fa292ed + b597748 commit b6e5636
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/python/plotly/_plotly_utils/colors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,3 +806,30 @@ def named_colorscales():
from _plotly_utils.basevalidators import ColorscaleValidator

return [c for c in ColorscaleValidator("", "").named_colorscales]


def get_colorscale(name):
"""
Returns the colorscale for a given name. See `named_colorscales` for the
built-in colorscales.
"""
from _plotly_utils.basevalidators import ColorscaleValidator

if not isinstance(name, str):
raise exceptions.PlotlyError("Name argument have to be a string.")

name = name.lower()
if name[-2:] == "_r":
should_reverse = True
name = name[:-2]
else:
should_reverse = False

if name in ColorscaleValidator("", "").named_colorscales:
colorscale = ColorscaleValidator("", "").named_colorscales[name]
else:
raise exceptions.PlotlyError(f"Colorscale {name} is not a built-in scale.")

if should_reverse:
return colorscale[::-1]
return colorscale
1 change: 1 addition & 0 deletions packages/python/plotly/plotly/colors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,5 @@
"plotlyjs",
"DEFAULT_PLOTLY_COLORS",
"PLOTLY_SCALES",
"get_colorscale",
]
Original file line number Diff line number Diff line change
Expand Up @@ -137,3 +137,30 @@ def test_make_colorscale(self):
self.assertRaisesRegexp(
PlotlyError, pattern2, colors.make_colorscale, color_list2, scale
)

def test_get_colorscale(self):

# test for incorrect input type
pattern = "Name argument have to be a string."
name = colors.sequential.haline

self.assertRaisesRegexp(PlotlyError, pattern, colors.get_colorscale, name)

# test for non-existing colorscale
pattern = r"Colorscale \S+ is not a built-in scale."
name = "foo"

self.assertRaisesRegex(PlotlyError, pattern, colors.get_colorscale, name)

# test non-capitalised access
self.assertEqual(colors.sequential.haline, colors.get_colorscale("haline"))
# test capitalised access
self.assertEqual(colors.diverging.Earth, colors.get_colorscale("Earth"))
# test accessing non-capitalised scale with capitalised name
self.assertEqual(colors.cyclical.mrybm, colors.get_colorscale("Mrybm"))
# test accessing capitalised scale with non-capitalised name
self.assertEqual(colors.sequential.Viridis, colors.get_colorscale("viridis"))
# test accessing reversed scale
self.assertEqual(
colors.diverging.Portland_r, colors.get_colorscale("portland_r")
)

0 comments on commit b6e5636

Please sign in to comment.