python-visualization / branca

This library is a spinoff from folium, that would host the non-map-specific features.
https://python-visualization.github.io/branca/
MIT License
111 stars 63 forks source link

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

Closed alessioarena closed 1 year ago

alessioarena commented 2 years ago

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 https://github.com/python-visualization/folium/issues/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: