Intro to Geographical Plotting
Tags: Choropleth Map, Data Science, Plotly, Data Visualization Tools, Python

Intro to Geographical Plotting

Photo by Kelsey Knight on Unsplash

In the field of data science, we often work on visualizing the data which gives us clear patterns about the data and makes it easy for analysis. Luckily python provides powerful data visualization tools for this purpose. In addition, it would be more interesting to visualize map-based data around the world or any specific country which gives us cool insights about the geographical data. Geographic maps are important because they provide context for our data values.

So, let’s check out Python’s Interactive Visualization tool — plotly .Using Plotly we can create beautiful Choropleth maps from the geo-data.

Choropleth maps:

Choropleth maps helps us to plot out information on a global or national wide. It allows us to see how a certain variable is distributed across a territory. In this blog, we will focus on using plotly for plotting choropleth maps.

Plotly

Plotly is an open-source library which allows us to create interactive plots that can be used in dashboards or websites. Plotly is also a company, that supports online and offline to host data visualisatoins. Let’s use offline mode for now as it is an open-source and as it makes easy to work inside our Python Jupyter notebook.

Geographical plotting using plotly is a bit challenging at first due to its various formats of data, so please refer this cheat sheet for syntax of all types of plotly plots.

Let’s get started with the below example to understand this concept…

Dataset from Kaggle:

Let’s find out Starbucks Stores across the globe and also on a national scale and visualize this data using choropleth maps. Dataset(directory.csv) can be downloaded from here. This dataset includes a record for every Starbucks store location currently in operation as of February 2017.

We will go through the following steps:

Import all the libraries and set our Jupyter notebook to work in offline mode. Extract Starbucks data to Dataframe using pandas. Create ‘data’ and ‘layout’ objects for ‘USA Country’ and plot the choropleth map. Create ‘data’ and ‘layout’ objects for ‘World Wide’ and plot the choropleth map.

Let’s first install plotly to Jupyter notebook

pip install plotly

Step 1:

import plotly.plotly as py

import plotly.graph_objs as go #importing graphical objects

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

download_plotlyjs allows plotly to work in offline mode.

init_notebook_mode connects Javascript to our notebook.

Step 2:

import pandas as pd

df = pd.read_csv('directory.csv')

Before moving to step 3, let’s quickly perform below tasks:

☑ Get subset data (US Country data) from the above dataset and assign it to a new data frame.

☑ Add one new column to the dataset — ‘Store Count’, to get the total number of stores for each state.

df_US = df[df['Country'] == 'US']

13608 entries for ‘US’ country

Now to add new column ‘Store Count’ to dataframe, we can use groupby() on ‘State/Province’ column as below

df_US['Store Count'] = df_US['Store Number'].groupby(df_US['State/Province']).transform('count')

State ‘AK’ has a total of 49 stores

df_US[df_US['State/Province'] == 'CA'][['State/Province','Store Count']].head(1) # to check num of stores in 'California'

‘CA’ has a total of 2821 stores

Step 3: Plotting ‘USA Country’ map

Let’s define our ‘data’ and ‘layout’ objects as below:

data = dict(type='choropleth',

locations = df_US['State/Province'],

locationmode = 'USA-states',

colorscale = 'Reds',

text = df_US['Brand'],

z = df_US['Store Count'],

colorbar = {'title':"Stores Count"}

)

type : Defines the type of the map(choropleth)

locations : Names of all states

locationmode : Specify the location by giving a Country name

colorscale : Displays a color map. (Refer below for more colorscales)

text : Displays a text when hovering over the map for each state element

z : Integer value which displays ‘Store Count’ for each state element

colorbar : Title for the right sidebar

colorscales:

[‘Greys’, ‘YlGnBu’, ‘Greens’, ‘YlOrRd’, ‘Bluered’, ‘RdBu’,

‘Reds’, ‘Blues’, ‘Picnic’, ‘Rainbow’, ‘Portland’, ‘Jet’,

‘Hot’, ‘Blackbody’, ‘Earth’, ‘Electric’, ‘Viridis’, ‘Cividis’]

layout = dict(title = 'Starbucks locations in USA Map',

geo = dict(scope='usa')

)

Now, we can use go.Figure() method to create an object for the map and then use iplot() method to generate the plot

choromap = go.Figure(data = [data],layout = layout)

iplot(choromap)

Interactive Choropleth map for ‘US’ country[Image by Author]

Cool! Our choropleth map for the ‘US’ country has been generated and from above we can see that each state displays text, number of stores and state names when hovering over each element on the map and the more concentrated the data is in one particular area, the deeper the shade of color on the map. Here ‘California’ has more number of stores (2821) and so the color is so deep.

Similar to Choropleth maps, we have another cool interactive map called ‘Scatter Plot’.

‘Scatter Plot’ provides each data point (which is represented as a marker point) on the map and location which is represented by the x (Longitude) and y(Latitude) columns.

We can use columns - ‘Longitude’ and ‘Latitude’ from our dataset to generate scatterplot.

Let’s create a scatter plot using the below code.

data = go.Scattergeo(

lon = df_US['Longitude'],

lat = df_US['Latitude'],

text = df_US['text'],

mode = 'markers',

marker = dict(symbol = 'star',size=5,colorscale = 'Reds'

),

marker_color = df_US['Store Count'],

)

layout = dict(title = 'Starbucks locations in USA Map',

geo_scope = 'usa'

)

choromap = go.Figure(data = [data],layout = layout)

iplot(choromap)

‘Star’ markers represent store locations for each state[Image by Author]

Step 4: Plotting ‘World’ map

Added a new column ‘Store Count’ as we did before. And also I have added one more column to dataset ‘CountryCode’ which has ISO 3(3 digits) code.

Here is the code for creating a choropleth world map...

data = dict(

type = 'choropleth',

locations = df['CountryCode'],

z = df['Store Count'],

text = df['Brand'],

colorbar = {'title' : 'Starbucks Stores - World Wide'},

)

layout = dict(

title = 'Stores Count',

geo = dict(

showframe = False,

projection = {'type':'natural earth'}

)

)

choromap = go.Figure(data = [data],layout = layout)

iplot(choromap)