Folium – Drawing Polygons with Distinct Colors Step-by-Step Guide

choroplethfoliumpython

I have trouble with my assignment. I have to draw over 100 polygons from the xml file and every of them has to have other color. I don't know how to accomplish it.
First I tried to draw polygons in loop, but eventually all polygons have the same color.

colors = []
for x in range(len(gminy)):
    color = np.random.randint(16, 256, size=3)
    color = [str(hex(i))[2:] for i in color]
    color = '#'+''.join(color).upper()
    colors.append(color)
cnt = 0
print(colors)
for x in gminy.iterrows():
    styl = {'fillColor':colors[cnt], 'color':'#000000', 'weight':0.1}
    folium.GeoJson(data=x[1]['geometry'], style_function = lambda y: styl).add_to(m)
    cnt += 1

Then I tried to create folium.Choropleth object with bins parameter set to 116 (that's the count of polygons) like this:

folium.Choropleth(
    geo_data=gminy,
    name='idTerytTerc',
    data=gminy_nr,
    columns=['idTerytTerc', 'Liczba'],
    key_on='feature.properties.idTerytTerc',
    fill_color='OrRd',
    fill_opacity=0.7,
    line_opacity=0.1,
    legend_name='Liczba mieszkańców',
    highlight=True,
    bins=116
).add_to(m)  
m

But when I did this I get an error message:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-53-42d7422910e7> in <module>
----> 1 folium.Choropleth(
      2     geo_data=gminy,
      3     name='idTerytTerc',
      4     data=gminy_nr,
      5     columns=['idTerytTerc', 'Liczba'],

C:\Programy\Anaconda\envs\geo\lib\site-packages\folium\features.py in __init__(self, geo_data, data, columns, key_on, bins, fill_color, nan_fill_color, fill_opacity, nan_fill_opacity, line_color, line_weight, line_opacity, name, legend_name, overlay, control, show, topojson, smooth_factor, highlight, **kwargs)
   1223             # We add the colorscale
   1224             nb_bins = len(bin_edges) - 1
-> 1225             color_range = color_brewer(fill_color, n=nb_bins)
   1226             self.color_scale = StepColormap(
   1227                 color_range,

C:\Programy\Anaconda\envs\geo\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: 'OrRd'

So, how can I fix this?

Best Answer

In your first attempt instead of adding the geojsons in a loop try adding them once with a style function which applies a distinct color to each polygon. Example (assuming gminy is a GeoPandas GeoDataFrame):

for x in gminy.index:
    color = np.random.randint(16, 256, size=3)
    color = [str(hex(i))[2:] for i in color]
    color = '#'+''.join(color).upper()
    gminy.at[x, 'color'] = color

def style(feature):
        return {
            'fillColor': feature['properties']['color'],
            'color': feature['properties']['color'],
            'weight': 1
        }

folium.GeoJson(data=gminy, style_function=style).add_to(m)