In [1]:
from IPython.display import HTML
import folium
import pandas as pd

In [2]:
def inline_map(map):
    """
    Embeds the HTML source of the map directly into the IPython notebook.
    
    This method will not work if the map depends on any files (json data). Also this uses
    the HTML5 srcdoc attribute, which may not be supported in all browsers.
    """
    map._build_map()
    return HTML('<iframe srcdoc="{srcdoc}" style="width: 100%; height: 510px; border: none"></iframe>'.format(srcdoc=map.HTML.replace('"', '&quot;')))

def embed_map(map, path="map.html"):
    """
    Embeds a linked iframe to the map into the IPython notebook.
    
    Note: this method will not capture the source of the map into the notebook.
    This method should work for all maps (as long as they use relative urls).
    """
    map.create_map(path=path)
    return HTML('<iframe src="files/{path}" style="width: 100%; height: 510px; border: none"></iframe>'.format(path=path))

In [3]:
df = pd.read_csv('../data/governors-challengers.csv')
df.head()


Out[3]:
state year twgov nameGov twch nameCh shareGov shareCh voterCnt
0 Alabama 2014 GovernorBentley Gov. Robert Bentley griffith2014 Parker Griffith 63.6 36.4 1174575
1 Alaska 2014 AkGovBillWalker Governor Bill Walker SeanParnellAK Sean Parnell 48.1 46.4 243597
2 Arizona 2014 dougducey Doug Ducey FredDuVal Fred DuVal 53.5 41.6 1492915
3 Arkansas 2014 AsaHutchinson Gov. Asa Hutchinson MikeRossUpdates Mike Ross 55.4 41.5 844442
4 California 2014 JerryBrownGov Jerry Brown neelkashkari Neel Kashkari 59.4 40.6 6496307

In [4]:
state_geo = r'../utilities/geodata/us-states.json'
states = folium.Map(location=[40, -99], zoom_start=4)
states.geo_json(geo_path=state_geo, data=df, data_out='gov_share.json',
                columns=['state', 'shareGov'],
                key_on='feature.properties.name',
                fill_color='PuRd', fill_opacity=0.7, line_opacity=0.2,
                legend_name='Incumbent Governor Vote Share (%)')
states.create_map(path='gov_share.html')

In [5]:
# inline_map()
HTML('<iframe srcdoc="{srcdoc}" style="width: 100%; height: 510px; border: none"></iframe>'.format(srcdoc=states.HTML.replace('"', '&quot;')))


Out[5]:

In [6]:
# embed_map()
HTML('<iframe src="files/{path}" style="width: 100%; height: 510px; border: none"></iframe>'.format(path='gov_share.html'))


Out[6]:

In [7]:
# embed_map() without 'files' IPYNB magic (!)
HTML('<iframe src="gov_share.html" style="width: 100%; height: 510px; border: none"></iframe>')


Out[7]: