Watch Me Code 3: Mapping with Folium

Folium is a Python wrapper library for the OpenStreetMaps api. It allows you to place data on a map in a variety of ways.


In [1]:
! pip install folium


Requirement already satisfied: folium in c:\anaconda3\lib\site-packages
Requirement already satisfied: Jinja2 in c:\anaconda3\lib\site-packages (from folium)
Requirement already satisfied: MarkupSafe in c:\anaconda3\lib\site-packages (from Jinja2->folium)

In [1]:
import folium
import pandas as pd
import random

In [2]:
# we need to center the map in the middle of the US. I googled for the location.
CENTER_US = (39.8333333,-98.585522)
london = (51.5074, -0.1278)
map = folium.Map(location=CENTER_US, zoom_start=4)
map


Out[2]:

Map Pins


In [3]:
# read in a data file of IP address to locations.
data = pd.read_csv('https://raw.githubusercontent.com/mafudge/datasets/master/clickstream/ip_lookup.csv')
data.sample(5)


Out[3]:
IP Country State City ApproxLat ApproxLng
10 56.216.127.219 USA NC Raleigh 35.779590 -78.638179
5 38.68.15.223 USA TX Dallas 32.776664 -96.796988
16 8.37.70.226 USA CA Los Angeles 34.052234 -118.243685
1 215.82.23.2 USA OH Columbus 39.961176 -82.998794
8 128.230.122.180 USA NY Syracuse 43.048122 -76.147424

In [5]:
# Let's place each location on the map
for row in data.to_records():
    pos = (row['ApproxLat'],row['ApproxLng'])
    marker = folium.Marker(location=pos, 
                    popup="%s, %s" % (row['City'],row['State'])
                          )
    map.add_child(marker)
map


Out[5]:

In [7]:
# Same thing with a different icon and colors. Icons come from http://fontawesome.io/icons/ but its an older version.
colors = ['red', 'blue', 'green', 'purple', 'orange', 'darkred',
            'lightred', 'beige', 'darkblue', 'darkgreen', 'cadetblue',
            'darkpurple', 'pink', 'lightblue', 'lightgreen',
            'gray', 'black', 'lightgray']
for row in data.to_records():
    pos = (row['ApproxLat'],row['ApproxLng'])
    marker = folium.Marker(location=pos, 
                    popup="%s, %s" % (row['City'],row['State']),
                    icon = folium.Icon(color = random.choice(colors), icon='user')
                          )
    map.add_child(marker)
map


Out[7]:

In [12]:
# There are other map tiles available. See https://folium.readthedocs.io/en/latest/quickstart.html
# Instead of Markers we use circles colors are HTML color codes http://htmlcolorcodes.com/
CENTER_US = (39.8333333,-98.585522)
map2 = folium.Map(location=CENTER_US, zoom_start=4)
for row in data.to_records():
    map2.add_child(folium.CircleMarker(location=(row['ApproxLat'],row['ApproxLng']), 
                    popup=row['City'], radius=10, color='#0000FF',  fill_color='#FF3333'))
    
map2


Out[12]:

Choropleths

Choropleths are cartographic overlays based on boundries defined in a geo JSON file.


In [13]:
# State level geo-json overlay choropleth
CENTER_US = (39.8333333,-98.585522)
state_geojson = 'WMC3-us-states.json'
map3 = folium.Map(location=CENTER_US, zoom_start=4, tiles=' Open Street Map')
map3.choropleth(geo_path=state_geojson)
map3


/opt/conda/lib/python3.7/site-packages/folium/folium.py:415: FutureWarning: The choropleth  method has been deprecated. Instead use the new Choropleth class, which has the same arguments. See the example notebook 'GeoJSON_and_choropleth' for how to do this.
  FutureWarning
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-35b538e24dfc> in <module>
      3 state_geojson = 'WMC3-us-states.json'
      4 map3 = folium.Map(location=CENTER_US, zoom_start=4, tiles=' Open Street Map')
----> 5 map3.choropleth(geo_path=state_geojson)
      6 map3

/opt/conda/lib/python3.7/site-packages/folium/folium.py in choropleth(self, *args, **kwargs)
    416         )
    417         from folium.features import Choropleth
--> 418         self.add_child(Choropleth(*args, **kwargs))
    419 
    420     def keep_in_front(self, *args):

TypeError: __init__() missing 1 required positional argument: 'geo_data'

In [16]:
states = pd.read_csv('https://raw.githubusercontent.com/jasonong/List-of-US-States/master/states.csv')
state_counts = pd.DataFrame( {'Counts' : data['State']. value_counts() } ).sort_index()
state_counts['StateCode'] = state_counts.index
state_data = states.merge(state_counts, how="left", left_on='Abbreviation', right_on='StateCode')
state_data = state_data[['Abbreviation','Counts']]
state_data = state_data.fillna(0)
state_data


Out[16]:
Abbreviation Counts
0 AL 0.0
1 AK 0.0
2 AZ 0.0
3 AR 0.0
4 CA 10.0
5 CO 0.0
6 CT 0.0
7 DE 0.0
8 DC 0.0
9 FL 1.0
10 GA 0.0
11 HI 0.0
12 ID 0.0
13 IL 0.0
14 IN 0.0
15 IA 0.0
16 KS 0.0
17 KY 0.0
18 LA 0.0
19 ME 0.0
20 MT 0.0
21 NE 0.0
22 NV 0.0
23 NH 0.0
24 NJ 1.0
25 NM 0.0
26 NY 4.0
27 NC 1.0
28 ND 0.0
29 OH 2.0
30 OK 0.0
31 OR 0.0
32 MD 0.0
33 MA 0.0
34 MI 0.0
35 MN 0.0
36 MS 0.0
37 MO 0.0
38 PA 0.0
39 RI 0.0
40 SC 0.0
41 SD 0.0
42 TN 0.0
43 TX 1.0
44 UT 1.0
45 VT 0.0
46 VA 2.0
47 WA 0.0
48 WV 0.0
49 WI 0.0
50 WY 0.0

In [25]:
CENTER_US = (39.8333333,-98.585522)
state_geojson = 'WMC3-us-states.json'
map3 = folium.Map(location=CENTER_US, zoom_start=4, tiles=' Open Street Map')
folium.Choropleth(geo_data=state_geojson,data=state_data, columns=['Abbreviation','Counts'], 
                key_on ='feature.id', fill_color='BuGn', legend_name='Website Visitors').add_to(map3)
map3


Out[25]:

In [19]:



Help on method choropleth in module folium.folium:

choropleth(*args, **kwargs) method of folium.folium.Map instance
    Call the Choropleth class with the same arguments.
    
    This method may be deleted after a year from now (Nov 2018).


In [23]:
# Here's a more straigtforward example with unemployment data:
unemployment = pd.read_csv('https://raw.githubusercontent.com/wrobstory/vincent/master/examples/data/US_Unemployment_Oct2012.csv')
state_geojson = 'WMC3-us-states.json'
map4 = folium.Map(location=CENTER_US, zoom_start=4, tiles=' Open Street Map')
folium.Choropleth(geo_data=state_geojson,data=unemployment, 
                columns=['State','Unemployment'], key_on ='feature.id', fill_color='YlGn', 
                legend_name='2012 US Unemployment Rate %').add_to(map4)
map4


Out[23]:

In [ ]: