Skip to content

color_brewer raises KeyError if user requests more colors than what the colormap has #104

@alessioarena

Description

@alessioarena

Problem
branca.utilities.color_brewer raises a non descriptive KeyError if the user requests more colors than the number of colors forming the selected colormap.

For example, RdYlBu is made of 11 individual colors. If the user requests more than 11 colors using the parameter n, this will trigger this error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-8-32dd8f641e66> in <module>
      6 print(branca.utilities.color_brewer('RdYlBu', 11))
      7 
----> 8 print(branca.utilities.color_brewer('RdYlBu', 12))
      9 

~\Miniconda3\envs\houselossmodel\lib\site-packages\branca\utilities.py in color_brewer(color_code, n)
    150     if not explicit_scheme:
    151         # Check to make sure that it is not a qualitative scheme.
--> 152         if scheme_info[base_code] == 'Qualitative':
    153             matching_quals = []
    154             for key in schemes:

KeyError: 'RdYlBu'

Minimal code

import branca
print(branca.__version__)
# 0.4.2

print(branca.utilities.color_brewer('RdYlBu'))
# ['#d73027', '#fc8d59', '#fee090', '#e0f3f8', '#91bfdb', '#4575b4']
# defaults to n=6

print(branca.utilities.color_brewer('RdYlBu', 11))
# ['#a50026', '#d73027', '#f46d43', '#fdae61', '#fee090', '#ffffbf', '#e0f3f8', '#abd9e9', '#74add1', '#4575b4', '#313695']

print(branca.utilities.color_brewer('RdYlBu', 12))
# KeyError

Other comments
This issue is linked to python-visualization/folium#1270

My understanding is that color_brewer is not meant to generate more colors than what is available. For that we can use branca.utilities.linear_gradient.
However, there are two issues I can see with this behaviour:

  • The KeyError raised is non descriptive and does not point to the real problem
  • I cannot see a straightforward way to know how many colors a specific colormap has, or to automatically return the maximum number of colors of that colormap

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions