Search code examples
pythonvisualizationfolium

How do I achieve this in Folium?


I am working on plotting the major earthquakes using Folium. I am able to plot all the instances, about 25000 of them. But the map starts looking very clumsy. I have used the following code:

map1 = folium.Map(location=[80., -180], zoom_start=1)
def color(magnitude):
if magnitude<6:
    col='green'
elif [(magnitude>6)&(magnitude<7.5)]:
    col='yellow'
else:
    col='red'
return col
fg=folium.FeatureGroup(name="Earthquake Locations")
for latitude,longitude,magnitude in zip(earthquakes['Latitude'][:30],earthquakes['Longitude'][:30],earthquakes['Magnitude'][:30]):
fg.add_child(folium.Marker(location=[latitude,longitude],popup=(folium.Popup(magnitude)),icon=folium.Icon(color=color(magnitude))))
map1.add_child(fg)

Now I want to make the plot look something like the first plot in the following R notebook: Notebook.

Can someone help me in achieving such a plot, where in the individual points are clustered and as we zoom, the points show up.

Thanks


Solution

  • Yes, you can. MarkerCluster is what you're after

    Give this a whirl

    import folium
    from folium.plugins import MarkerCluster
    
    map1 = folium.Map(location=[80., -180], zoom_start=1)
    
    def color(magnitude):
        if magnitude<6:
            col='green'
        elif [(magnitude>6)&(magnitude<7.5)]:
            col='yellow'
        else:
            col='red'
        return col
    
    map1.add_child(MarkerCluster(locations=list(zip(earthquakes['Latitude'], 
                                     earthquakes['Longitude'])),
                                     popups=earthquakes['Magnitude'].astype(str),
                                     icons=[color(m) for m in earthquakes['Magnitude']]))
    
    map1
    

    enter image description here