In [2]:
import pandas as pd
import cufflinks as cf
import numpy as np
from IPython.display import display,HTML
from plotly.widgets import GraphWidget
from ipywidgets import widgets
In [3]:
df = pd.read_csv('http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/'
'examples/gapminder/data/'
'gapminderDataFiveYear.txt', sep='\t')
# If we look here at the columns of the table, we can see that variable is truncated. Let's fix this.
df.columns = ['Country', 'Year', 'Population',
'Continent', 'Life Expectancy', 'GDP per Capita']
numerical_cols = ['Population','Life Expectancy','GDP per Capita']
minY,maxY = int(df.Year.min()), int(df.Year.max())#Used for boundary interact later
# colormap = dict(zip(df.Continent.unique(),Spectral5)) #Specify colormap for every continent
df['ori_Population'] = df.Population
df['Population'] = df['ori_Population'] / df.ori_Population.max() * 100 #Normalize the size of the bubble chart
In [9]:
p = df[df.Year == 2007].iplot(kind='bubble',x='Life Expectancy',y='GDP per Capita',
categories='Continent',size='Population',title='2007')
In [11]:
circle = GraphWidget('https://plot.ly/~napitupulu.jon/90')
In [12]:
circle
In [ ]:
circle = GraphWidget(p.resource)
In [ ]:
l = df[df.Country == 'China'].iplot(kind='scatter',title='China',
x='Year',y='GDP per Capita')
In [ ]:
line = GraphWidget(l.resource)
In [9]:
line = GraphWidget('https://plot.ly/~napitupulu.jon/94')
In [10]:
line
In [13]:
def create_dropdown(value,description):
return (widgets.Dropdown(
options=numerical_cols,
value=value,
description=description))
xaxis = create_dropdown('Life Expectancy','xaxis')
yaxis = create_dropdown('GDP per Capita', 'yaxis')
size = create_dropdown('Population', 'size')
year = widgets.IntSlider(min=minY,max=maxY,step=5,
value=2007,description='year')
year.width = 150
display(year)
display(xaxis)
display(yaxis)
display(size)
In [14]:
from IPython.display import display, clear_output
def update_circle(val):
clear_output()
dfY = df[df.Year == year.value]
circle.restyle({'x':[dfY[xaxis.value].tolist()],
'y':[dfY[yaxis.value].tolist()],
'size':[dfY[size.value].tolist()]})
circle.relayout({'title':str(year.value)})
In [15]:
year.observe(update_circle)
xaxis.observe(update_circle)
yaxis.observe(update_circle)
size.observe(update_circle)
In [16]:
def update_line(widget, msg):
clear_output()
point = msg[0]
country = df[(df[xaxis.value] == point['x']) &
(df[yaxis.value] == point['y'])].Country.tolist()[0]
y = df.ix[(df['Country'] == country),yaxis.value].tolist()
line.restyle({'y':[y]})
line.relayout({'title':country})
In [17]:
circle.on_hover(update_line)