Search code examples
pythonmatplotlibgeopandasfoliumchoropleth

Error with cmap from a matplotlib defined list of colors in Folium - choropleth map


I'm triying to pass a customize list of colors to my choropleth map with geopandas.explore, but i get the error:

UnboundLocalError: local variable 'binning' referenced before assignment

if I specified a given list of colors ex: cmap= 'Blues', it displays with no problem

I copy the code below

import geopandas as gpd
import matplotlib.colors
import folium

color_list= matplotlib.colors.LinearSegmentedColormap.from_list('custom', [ "#e1f2f2", "#A8DCDC", "#115F5F"]) 

ventas_map= data.explore(column='ventas', scheme='Quantiles', cmap= color_list, tiles= 'OpenStreetMap', k=5, legend_kwds={'caption': 'ventas[$]','colorbar': True ,'scale': False}, name= 'ventas')

Anyone know how to solve it?


Solution

  • I found the right way to do this, I defined the color list with the following function, and then use the name list I gave between 'color_list' in the cmap atribute in geopandas.explore function

    def colors2cmap(*args, name=None):
    """Create a colormap from a list of given colors.
    
    Parameters:
        *args: Arbitrary number of colors (Named color, HEX or RGB).
        name (str): Name with which the colormap is registered.
    
    Returns:
        LinearSegmentedColormap.
    
    Examples:
        >>> colors2cmap('darkorange', 'white', 'darkgreen', name='test')
    """
    if len(args) < 2:
        raise Exception("Give at least two colors.")
    
    cmap_data = [matplotlib.colors.to_hex(c) for c in args]
    
    cmap = matplotlib.colors.LinearSegmentedColormap.from_list(name, cmap_data)
    plt.register_cmap(name, cmap)
    
    return cmap }
    

    And called the function:

     colors2cmap("#e1f2f2", "#A8DCDC", "#115F5F", name='color_list')