Search code examples
pythongeojsonfoliumchoropleth

How to highlight different areas in a geojson file?


I am using folium to plot some data on a map. I have a csv file with some data which includes some addresses with their city districts and pincode.I have around 450 data in the csv file. Following is the type of data in the csv file:

Using the pincodes in the data i need to plot the density of the addresses in each pincode. I used the following code to get the required data from the csv:

df_file = r'C:\Users\Desktop\file.csv'
df_input = pd.read_csv(df_file,index_col=0)
# print(df_input)
df1 = df_input.groupby('ZIP').count()
df1 = pd.DataFrame(df1,columns=['PLACE'])
df1.reset_index(inplace=True)
df1.rename(columns={'ZIP':'PIN','PLACE':'COUNT'},inplace=True)
df1.sort_values(by='COUNT',inplace=True,ascending=False)
print(df1)

Now I just need to plot the count according to the pincode and I have a geojson file available.

I tried to plot this on the map using the following code:

geo = r'C:\Users\file.geojson'
my_map = folium.Map(location = coord,zoom_start=10)

folium.Choropleth(
    geo_data = geo,
    data = df1,
    columns = ['PIN','COUNT'],
    key_on = 'feature.properties.PIN_NAME',
    fill_color = 'YlOrRd',
    fill_opacity ='0.3',
    line_opacity ='0.8',
    legend_name = 'Density').add_to(my_map)
my_map.add_child(folium.map.LayerControl())
my_map.save(r'map.html')

Solution

  • You just need to change the type of the column "PINCODE" of your dataframe df1 to string : df1["PIN"] = df1["PIN"].astype("str")

    If you want to add the name of the regions on the map, you need to modify your code like this :

    choropleth = folium.Choropleth(
        geo_data = geo,
        data = df1,
        columns = ['PIN','COUNT'],
        key_on = 'feature.properties.PIN_NAME',
        fill_color = 'YlOrRd',
        fill_opacity ='0.3',
        line_opacity ='0.8',
        legend_name = 'Density').add_to(my_map)
    my_map.add_child(folium.map.LayerControl())
    choropleth.geojson.add_child(
        folium.features.GeoJsonTooltip(['PIN_NAME'], labels=False))
    

    The choropleth map looks like that in my Jupyter Notebook : enter image description here