Search code examples
pythonjsonvisualizationfolium

How do assign color to Folium Map based on another Column value?


I have the following data structure (700 rows, 6 clusters), an example is shown below.

uID LAT         LNG         cluster_label
1   29.488112   -12.144520  1
3   11.143642   -30.761047  0
10  21.230476   -25.757441  1
16  61.196442   -23.394233  1

I want to graph it on a map using folium which I have done successfully. However, I am struggling to figure out how to change the marker color based on the cluster_label column. Below is my map code.

#Create map
m = folium.Map(location=[40, -90], zoom_start=4)

#Create loop to add marker one by one
for i in range(0,len(df4)):
   folium.Marker(
      location=[df4.iloc[i]['LAT'], df4.iloc[i]['LNG']],
      popup = df4.iloc[i]['uID'],
   ).add_to(m)

#Show map
m

I've tried adding

color = df4['cluster_label']

to the code but am getting "TypeError: Object of type Series is not JSON serializable".

I've also tried defining a function with if statements assigning color based on the cluster_label value and then add getcolor to the code (based on another SO post) but that did not work.

Any help is greatly appreciated.


Solution

  • Sample data is used from the reference of another visualization library, plotly. The reason is that we have the necessary data for clusters and it is easier to understand the impact of the size of the markers on the map if the number of markers is a little larger. To color-code the clusters according to their values, you can create an arbitrary color list and specify the color of it with the folium icon. The color names that can be used for icons are limited to the following

    ['red', 'blue', 'green', 'purple', 'orange', 'darkred', 'lightred', 'beige',
     'darkblue', 'darkgreen', 'cadetblue', 'darkpurple', 'white', 'pink',
     'lightblue', 'lightgreen', 'gray', 'black', 'lightgray']
    
    import pandas as pd
    import numpy as np
    
    # plotly reference:https://plotly.com/python/lines-on-maps/
    df_airports = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
    df_airports['cluster_label'] = pd.cut(df_airports['cnt'], 6, retbins=True, labels=[0,1,2,3,4,5])[0]
    
    colors = ['lightgray', 'red', 'blue', 'green', 'purple', 'orange']
    
    import folium
    
    m = folium.Map(location=[40, -90], zoom_start=5)
    
    for row in df_airports.itertuples():
    
        folium.Marker(
            location=[row.lat, row.long],
            popup=row.iata,
            icon=folium.Icon(color=colors[row.cluster_label])        
        ).add_to(m)
    
    m
    

    enter image description here