In [2]:
%matplotlib inline
import requests as r
import json
import re
import pandas as pd
from ggplot import *
from IPython.display import HTML
In [ ]:
HTML('''<script>
code_show=true;
function code_toggle() {
if (code_show){
$('div.input').hide();
} else {
$('div.input').show();
}
code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
The raw code for this IPython notebook is by default hidden for easier reading.
To toggle on/off the raw code, click <a href="javascript:code_toggle()">here</a>.''')
In [ ]:
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('"', '"')))
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 [ ]:
import folium
map = folium.Map(location=[30.5171, 0.1062], width=1000, height = 500, zoom_start=2)
#map.simple_marker([45.3288, -121.6625], popup='My Popup Message')
map.circle_marker(location=[45.5215, -122.6261], radius=800,
popup='My Popup Info', line_color='#ff0000',
fill_color='#3186cc', fill_opacity=0.2)
inline_map(map)
In [ ]:
import pandas as pd
df = pd.DataFrame([{"runner_id": "bob", "time_A": 30,
"time_B": 25, "speed_A": 5, "speed_B": 10},
{"runner_id": "mary", "time_A": 29,
"time_B": 19, "speed_A": 8, "speed_B": 12}])
from rpy2.robjects.lib import grid
from rpy2.robjects.lib import ggplot2
import rpy2.robjects.pandas2ri
rpy2.robjects.pandas2ri.activate()
p = ggplot2.ggplot(rpy2.robjects.conversion.py2ri(df)) + \
ggplot2.geom_point(ggplot2.aes_string(x="time_A",y="speed_A"),colour="#ff0000") + \
ggplot2.geom_point(ggplot2.aes_string(x="time_B",y="speed_B"),colour="#0000ff") + \
ggplot2.scale_x_continuous("time") + \
ggplot2.scale_y_continuous("speed")
p.plot()
In [ ]:
import matplotlib.pyplot as plt, mpld3
mpld3.enable_notebook()
p = plt.plot([3,1,4,1,5], 'ks-', mec='w', mew=5, ms=20)
p
In [ ]:
js_loader = """
function verifyJSLoaded(){
var jsapiLoaded = (typeof google === 'object' && typeof google.maps === 'object');
console.log("Google API Loaded: " + jsapiLoaded);
return jsapiLoaded;
}
function loadScript() {
if (!verifyJSLoaded()) {
console.log('Loading Google API.');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?sensor=false&libraries=visualization&callback=console.log";
document.body.appendChild(script);
}
}
loadScript();
"""
Javascript(js_loader)
In [ ]:
html_template = '<div id="{0}" style="width: 1024px; height: 768px"></div>'
#This is to make sure the JS gets loaded before we try to load the maps
time.sleep(1)
In [ ]:
def gen_javascript(gJSONs, div_id):
"""
Generates javascript to draw a heatmap with Google Maps API.
"""
# Creates Javascript objects which will comprise geoData.
coords = ',\n '.join(["new google.maps.LatLng(%s, %s)" % tuple(pair) for pair in gJSONs])
template_jscript = """
var geoData = [
%s
];
var map, heatmap;
function hmap_initialize() {
var mapOptions = {
zoom: 1,
center: new google.maps.LatLng(30.5171, 0.1062),
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('%s'),
mapOptions);
var pointArray = new google.maps.MVCArray(geoData);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
}
hmap_initialize();
"""
return template_jscript % (coords, div_id)
In [ ]:
HTML(html_template.format('map_001'))
In [ ]:
jscript = gen_javascript(tweetsWithLoc['geo'].map(lambda x: x['coordinates']),'map_001')
Javascript(jscript)
In [ ]:
Javascript(
'''
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
''')
In [ ]:
Javascript('''
function verifyJSLoaded() {
return false;
}
function loadScript() {
if (!verifyJSLoaded()) {
console.log('Loading Tweeter API.');
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https:////platform.twitter.com/widgets.js";
document.body.appendChild(script);
}
}
loadScript();
''')
In [62]:
HTML('<script type="text/javascript" src="//www.google.com/trends/embed.js?hl=en-US&q=shellshock&date=today+1-m&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>''')
Out[62]:
In [63]:
from IPython.display import Image
In [64]:
Image('googleTrend-shellshock.png')
Out[64]:
In [ ]: