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
110 stars 63 forks source link

fix calculation of color index #134

Closed MxMartin closed 9 months ago

MxMartin commented 11 months ago

The current code returns erroneous colors. To make it clear I took the current implementation and put it into a separate function

def new_implementation(value):
    if value <= index[0]:
        return 0
    if value >= index[-1]:
        return len(index) - 1
    return next(i for i, v in enumerate(color_map.index) if v > value) -1

def current_implementation(value):
    if value <= index[0]:
        return 0
    if value >= index[-1]:
        return len(index) - 1
    return len([u for u in index if u < value]) - 1

index = [1, 2, 4]
colors = ["black", 'purple', 'red']

print("value", "current implementation", "new implementation")
for i in range(-2, 5):
    print(i, "\t", current_implementation(i), "\t", new_implementation(i)) 

returns:

value current_implementation new_implementation
-2   0   0
-1   0   0
0    0   0
1    0   0
2    0   1
3    1   1
4    2   2
5    2   2

you will notice that for value 2 the current implementation would return color 0, even though value 2 is at index 1 in index.

Or for

index = [2, 4, 5]

this returns

value current_implementation new_implementation
-2   0   0
-1   0   0
0    0   0
1    0   0
2    0   0
3    0   0
4    0   1
5    2   2
6    2   2
7    2   2

i.e. for index 4 we get color 0 and for index 5 color 2. Color 1 is never returned though it should be returned vor value 4

Last but not least I added a check on init to make sure the index is in order

Conengmo commented 9 months ago

Superseded by https://github.com/python-visualization/branca/pull/141