Rebecca James
Rebecca James

Reputation: 385

How to add text to folium choropleth maps

I am using sample data from geopandas for this example. But basically what I want to do is have a choropleth map with text displayed on it by default.

Currently, I have used tooltip='BoroCode' to display the text I need however, I don't want the text displayed only when you hover over the area. I'd like it to be displayed all the time.

import folium
import branca.colormap as cmp
import geopandas

path_to_data = geopandas.datasets.get_path("nybb")
gdf = geopandas.read_file(path_to_data)

# create map
m= folium.Map(location=[40.730610, -73.935242])
# add boroughs
gdf.explore(
     m=m,
     column="BoroName", 
     scheme="naturalbreaks",  
     legend=True, 
     k=10,
     cmap='winter',
     legend_kwds=dict(), 
     name="boroughs" ,
    tooltip='BoroCode'
)

folium.LayerControl().add_to(m) 
m  

Upvotes: 0

Views: 908

Answers (1)

r-beginners
r-beginners

Reputation: 35205

I don't have enough experience with geopandas, but in this case, gdf.explore() doesn't seem to have the ability to add annotations, so you can add a marker with html format text set with an icon on the folium side. If the map coordinate system in geopandas is The map coordinate system of geopandas is not in a format that can be used by folium, so it is converted. Then, the center point of the borough is obtained. A warning will be displayed if this center point is not correct. I think the solution to avoid this warning is to use the actual center point.

import folium
from folium.features import DivIcon
import branca.colormap as cmp
import geopandas

path_to_data = geopandas.datasets.get_path("nybb")
gdf = geopandas.read_file(path_to_data)
gdf = gdf.to_crs(epsg=4326) 
gdf['centroid'] = gdf.centroid
gdf['lat'] = gdf['centroid'].map(lambda p: p.y)
gdf['lon'] = gdf['centroid'].map(lambda p: p.x)

m = folium.Map(location=[40.730610, -73.935242])

for i, row in gdf.iterrows():
  folium.map.Marker(
      [row['lat'],row['lon']],
      icon=DivIcon(
          icon_size=(100,24),
          icon_anchor=(0,0),
          html=f'<div style="font-size:16px; color:white;">{row["BoroName"]}</div>',
      )
  ).add_to(m)

#add boroughs
gdf.explore(
    m=m,
    column="BoroName",
    scheme="naturalbreaks",  
    legend=True, 
    k=10,
    cmap='winter',
    legend_kwds=dict(), 
    name="boroughs",
    tooltip='BoroName'
)

folium.LayerControl().add_to(m)
m

enter image description here

Upvotes: 1

Related Questions