Data Visualization - Geographical Plotting
Geographical plotting is usually challenging due to the various formats data can come in. In this section we will focus on using plotly
for plotting. Matplotlib also has a basemap
extension.
Choropleth US Maps
Get imports and set everything up to be working offline.
import plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
Now set up everything so that the figures show up in the notebook:
Now we need to begin to build our data dictionary. Easiest way to do this is to use the dict() function of the general form:
type = 'choropleth'
locations = list of states
locationmode = 'USA-states'
colorscale=
either using a predefined string:
'pairs' | 'Greys' | 'Greens' | 'Bluered' | 'Hot' | 'Picnic' | 'Portland' | 'Jet' | 'RdBu' | 'Blackbody' | 'Earth' | 'Electric' | 'YIOrRd' | 'YIGnBu'
or create a custom colorscaletext=
list or array of text to display per pointz=
array of values on z axis (color of state)colorbar = {'title':'Colorbar Title'})
Here is a simple example:
data = dict(type = 'choropleth',
locations = ['AZ','CA','NY'],
locationmode = 'USA-states',
colorscale= 'Portland',
text= ['text1','text2','text3'],
z=[1.0,2.0,3.0],
colorbar = {'title':'Colorbar Title'})
Then we create the layout nested dictionary:
Then we use:
go.Figure(data = [data],layout = layout)
to set up the object that finally gets passed into iplot()
Real Data Choropleth US Map
Now let's show an example with some real data as well as some other options we can add to the dictionaries in data and layout.
Now our data dictionary with some extra marker and colorbar arguments:
data = dict(type='choropleth',
colorscale = 'ylorrd',
locations = df['code'],
z = df['total exports'],
locationmode = 'USA-states',
text = df['text'],
marker = dict(line = dict(color = 'rgb(255,255,255)',width = 2)),
colorbar = {'title':"Millions USD"}
)
And our layout dictionary with some more arguments:
layout = dict(title = '2011 US Agriculture Exports by State',
geo = dict(scope='usa',
showlakes = True,
lakecolor = 'rgb(85,173,240)')
)
choromap = go.Figure(data = [data],layout = layout)
iplot(choromap)
Real Data Choropleth World Map
Now let's see an example with a World Map:
data = dict(
type = 'choropleth',
locations = df['CODE'],
z = df['GDP (BILLIONS)'],
text = df['COUNTRY'],
colorbar = {'title' : 'GDP Billions US'},
)
layout = dict(
title = '2014 Global GDP',
geo = dict(
showframe = False,
projection = {'type':'mercator'}
)
)