Your guide to folium markers
Let’s start with Vehicle Collisions in NYC dataset from kaggle and limit it to 2015 data only (the steps are listed here).
We will work with df_2015 dataset, which was created using code below.
It is very easy to start working in folium. Just google location’s latitude/longitude and paste it into folium.Map(location=[…, …]). The result will be an interactive map that looks like this.
If the map needs to be smaller, it can be adjusted with Figure from branca.element. We can also specify what zoom level we want to start with and zoom min and max levels.
We can also adjust the map size with width, height, left and top arguments, but it will leave the white space around the map like in the screenshot below.
We can change how the map looks by using folium.TileLayer or tiles. The default setting is OpenStreetMap, but other Stamen Terrain, Stamen Toner, Stamen Water Color, cartodbpositron and cartodbdark_matter tiles are available. Stamen Terrain and OpenStreetMap are my favorite tiles.
Let’s try adding markers to the map. Set up variables max_PEDESTRIANS_INJURED, max_CYCLISTS_INJURED and max_MOTORISTS_INJURED equal to pandas dataframe with max persons injured in a given category.
We will then pass latitude and longitude to folium.Marker to show the location on the map. The output of max_CYCLISTS_INJURED has two rows and we will need to identify them by index.
It’s difficult to see the difference between the markers, so let’s add icon=folium.Icon to markers and specify icon’s color and display. Location of an accident with max pedestrians injured has red icon, locations with max cyclists injured have green icon, and location of an accident with max motorists injured has blue icon.
Available icon colors are: ‘red’, ‘blue’, ‘green’, ‘purple’, ‘orange’, ‘darkred’, ‘lightred’, ‘beige’, ‘darkblue’, ‘darkgreen’, ‘cadetblue’, ‘darkpurple’, ‘white’, ‘pink’, ‘lightblue’, ‘lightgreen’, ‘gray’, ‘black’, ‘lightgray’.
These icons are good enough, but I’d like to change them to something more meaningful. For example, i want a bicycle icon for accidents involving cyclists. By default, icons are glyphicon from bootstrap, and their full list can be found here. Glyphicons are useful, but limited in range. To get more variety, we can use icons from font-awesome. The list of font-awesome icons is here. To use font-awesome icons, we need to specify prefix=‘fa’.
Additionally, we can add tooltip and popup. Tooltip allows to display a text when hovering over the marker. Popup is a label for the marker that is visible after the marker is clicked on.
Now let’s add more information to the popup about how many people were injured in any given category and how many people were injured overall.
At last, let’s add folium.LatLngPopup() so we can get latitude/longitude information by clicking anywhere on the map.
Now, our map is complete!
Additional resources: