Create Folium map with discrete color fill

Viewed 741

I would like to fill in a Folium map with discrete color values. But every shape is returned with the same value (i.e. - the same color)

Name           Fill_Color              Geometry
A              orange                  ....
B              yellow                  ....
C              purple                  ....
D              red                     ....

m = folium.Map(location=[40.6725, -73.985], zoom_start=14, tiles='CartoDB positron')
title_html = '''
              <h3 align="center" style="font-size:16px"><b>{}</b></h3>
             '''.format('Gowanus Projects')

for _, r in gzones.iterrows():

    sim_geo = gpd.GeoSeries(r['geometry'])
    geo_j = sim_geo.to_json()
    geo_j = folium.GeoJson(data=geo_j,
                           style_function=lambda x: {'fillColor': r['fill_color']})
    folium.Tooltip(r['Name']).add_to(geo_j)
    geo_j.add_to(m)
m.get_root().html.add_child(folium.Element(title_html))
m
1 Answers

The question is, if you use geopandas that contain geometry information, it will be internally converted to geojson when referenced in the style function, so the reference will be r['properties']['fill_color']. Also, no looping is required and the entire data frame can be handled. I have modified this official sample to fit your code.

import geopandas

url = ("https://raw.githubusercontent.com/python-visualization/folium/master/examples/data")
nybb = f"{url}/nybb.zip"
boros = geopandas.read_file(nybb)

# colors added
fill_color = ['orange','yellow','purple','red','blue']
boros['fill_color'] = fill_color

boros

    BoroCode    BoroName    Shape_Leng  Shape_Area  geometry    fill_color
0   5   Staten Island   330454.175933   1.623847e+09    MULTIPOLYGON (((970217.022 145643.332, 970227....   orange
1   3   Brooklyn    741227.337073   1.937810e+09    MULTIPOLYGON (((1021176.479 151374.797, 102100...   yellow
2   4   Queens  896875.396449   3.045079e+09    MULTIPOLYGON (((1029606.077 156073.814, 102957...   purple
3   1   Manhattan   358400.912836   6.364308e+08    MULTIPOLYGON (((981219.056 188655.316, 980940....   red
4   2   Bronx   464475.145651   1.186822e+09    MULTIPOLYGON (((1012821.806 229228.265, 101278...   blue

import folium
from folium.features import GeoJsonTooltip

m = folium.Map(location=[40.6725, -73.985], zoom_start=10, tiles='CartoDB positron')
title_html = '''
              <h3 align="center" style="font-size:16px"><b>{}</b></h3>
             '''.format('Gowanus Projects')

tooltip = GeoJsonTooltip(
    fields=["BoroName"],
    labels=True
    )

folium.GeoJson(boros,
               style_function=lambda x: {'fillColor':x['properties']['fill_color']},
               tooltip=tooltip
               ).add_to(m)
m.get_root().html.add_child(folium.Element(title_html))
m

enter image description here

Related