In [1]:
import sys # system module
import pandas as pd # data package
import matplotlib.pyplot as plt # graphics module
import datetime as dt # date and time module
import numpy as np # foundation for Pandas
import seaborn.apionly as sns # fancy matplotlib graphics (no styling)
from pandas.io import data, wb # worldbank data
import plotly.plotly as py # importing stuff to Plotly
from ipywidgets import interact, interactive, fixed
import ipywidgets as widgets
# plotly imports
from plotly.offline import iplot, iplot_mpl # plotting functions
import plotly.graph_objs as go # ditto
import plotly # just to print version and init notebook
import cufflinks as cf # gives us df.iplot that feels like df.plot
cf.set_config_file(offline=True, offline_show_link=False)
# these lines make our graphics show up in the notebook
%matplotlib inline
plotly.offline.init_notebook_mode()
# check versions (overkill, but why not?)
print('Python version:', sys.version)
print('Pandas version: ', pd.__version__)
print('Plotly version: ', plotly.__version__)
print('Today: ', dt.date.today())
In [2]:
gini = wb.download(country= 'all',indicator = ['SI.POV.GINI'],start=1990, end=2013)
In [3]:
url = "http://unstats.un.org/unsd/methods/m49/m49alpha.htm"
iso = pd.read_html(url, attrs={"border": "0", "cellpadding": "2"}, header=0)[0]
iso = iso.rename(columns={"ISO ALPHA-3 code": "ISO",
"Country or area name": "country"})
iso = iso.drop("Numerical code", axis=1)
iso.head()
Out[3]:
In [4]:
iso['country']=iso['country'].replace('United States of America','United States')
iso[-15:]
Out[4]:
In [8]:
gini1 = gini.reset_index()
gini1.head(5)
Out[8]:
In [9]:
gini2 = pd.merge(gini1,iso,how='left',on='country')
In [10]:
gini2.head(5)
Out[10]:
In [11]:
gini2 = gini2.set_index(['ISO','year'])
gini2.columns = ['Country','Gini']
In [12]:
gini2 = gini2.reset_index()
In [13]:
gini2.head(5)
Out[13]:
In [14]:
gini3 = gini2.pivot_table(values = 'Gini', index = 'ISO',columns = 'year')
gini3.head(5)
gini4 = gini3.copy()
In [15]:
gini5 = gini4.T.fillna(method='pad').T
In [16]:
gini5.head(5)
Out[16]:
In [17]:
gini6 = gini5.reset_index()
In [23]:
gini7 = pd.merge(gini6,iso,how='left',on='ISO')
In [24]:
gini7 = gini7.set_index('ISO')
In [25]:
gini7.head(5)
Out[25]:
In [26]:
years = list(range(1990,2011))
In [30]:
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.3, 'rgb(188,189,220)'],
[0.4, 'rgb(158,154,200)'],[0.6, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
def map_gini(year):
trace = dict(type="choropleth",
locations=list(gini5.index), # use ISO names
z=gini7[str(year)], # defines the color
colorscale= scl, # change pallette
text=gini7['country'], # change text on hover
)
layout = dict(geo=dict(
showframe = False,
showcoastlines = True),
width=900, height=700)
# reuse the same layout
iplot(go.Figure(data=[trace], layout=layout), link_text="")
interact(map_gini, year=widgets.IntSlider(min=1993,max=2011,step=1));
In [ ]:
In [ ]:
In [ ]: