Using Python for geographical plotting
By: Jayashree Domala
Tags: Plotly, Python, Data Science, Data Visualization, Data

Using Python for geographical plotting

A guide to understanding and create geographical plots for data analysis.

What is geographical plotting?

Geographical plotting is used for world maps and also for different states of the countries. It is useful when map-based data has to be analyzed and draw insights. An application area of this is for visualization export and import data of goods.

What is used to create geographical plots?

Plotly will be used for plotting. The reason being that it creates interactive plots.

To know about Plotly in detail, check my article here.

How to import packages?

The plotly package is imported. Along with this few modules from plotly offline are also imported since we are using in the offline mode. The Pandas package is imported for dealing with dataframes.

>>> import pandas as pd

>>> import plotly as py

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

Then to assure that the plots are displayed inside the notebook, write the below code.

>>> init_notebook_mode(connected=True)

Choropleth maps

Choropleth map is a map that contains polygons that are colored. It helps to visualize how a variable varies across a geographic area.

For creating choropleth maps, we need to create a data dictionary using the dict() method. This dictionary contains the type, the locations which are essentially the states or countries passed as an array and the location mode. Then the colorscale is defined. The different pre-defined color scales are: ‘pairs’, ‘Greys’, ‘Greens’, ‘Bluered’,’Hot’,’Picnic’,’Portland’,’Jet’,’RdBu’,’Blackbody’,’Earth’, ‘Electric’,’YIOrRd’,’YIGnBu’. Then the text values are given. These values are just the names that appear when hovered over the location. Then an array is passed as an argument for z. The values in the array are the numbers that should be associated corresponding to the colors. Then the final argument is the colorbar which takes a dictionary as a value. For the key ‘title’ we can mention what the title of the color bar should be.

Here the countries of the Asia continent will be considered for plotting.

>>> data = dict(type = 'choropleth',

locations =['india','srilanka','nepal','Bangladesh','china','pakistan','bhutan','myanmar'],

locationmode = 'country names',

colorscale= 'Picnic',

text= ['IND','SLK','NEP','BAN','CHI','PAK','BHU', 'MYN'],

z=[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0],

colorbar = {'title':'Country Colours'})

Now a layout object is created. This layout is a nested dictionary. The scope is mentioned here.

>>> layout = dict(geo={'scope':'asia'})

Now an object is created using go.Figure() function so that it can be passed into the iplot() method. For doing this, another import has to be done of graph objects from plotly. After importing, in the go.Figure() method, the data and layout are passed. And it is plotted using the iplot() method.

>>> import plotly.graph_objs as go >>> chmap = go.Figure(data=[data],layout=layout)

>>> iplot(chmap)

Using real data for country plotting

The election data is used to understand how choropleth maps can be created for real data. The data used is election data of the United States.

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

df.head()

Now we will create the data dictionary. Here instead of writing the state names and text values, the dataframe columns will be called directly. So for locations, the ‘Sate Abv’ column will be passed and the location mode will be USA-states since the dataset deals with only US states. Next, the z value will get the column of the voting age population to show these details according to the corresponding colors. The text values will also get the ‘state’ column of the dataframe. Then the colorbar title is given as Voting age population since that is what it is depicting.

An extra argument is added which is the marker. It is a nested dictionary that defines how the marker will be. The color and width are defined. The marker just defines how the borders will be connected to the different locations.

>>> data = dict(type='choropleth',

colorscale = 'Earth',

locations = df['State Abv'],

locationmode = 'USA-states',

z = df['Voting-Age Population (VAP)'],

text = df['State'],

marker = dict(line = dict(color = 'rgb(255,255,255)',width = 1)),

colorbar = {'title':"Voting Age Population (VAP)"})

Now the layout dictionary is created. The title of the plot is passed along with the scope. The scope is ‘usa’. Additionally, another argument is mentioned ‘showlakes’. It shows the lakes and the lakecolor is also mentioned which is blue (written as rgb value).

>>> layout = dict(title = 'Election Voting Data',

geo = dict(scope='usa',

showlakes = True,

lakecolor = 'rgb(85,173,240)')

) >>> chmap = go.Figure(data = [data],layout = layout)

>>> iplot(chmap)

Using real data for world plotting

Now a real dataset is used of the world power consumption so as to understand how the plotting happens when the entire world is taken into consideration.

>>> df2 = pd.read_csv('world_power.csv')

>>> df2.head()

As done previously, the data dictionary and layout dictionary is created. In the layout, an extra argument projection type is mentioned. It decided how the locations will look. The various options can be found in the official documentation. The link is provided at the end of the article.

>>> data = dict(

type = 'choropleth',

colorscale = 'Jet',

locations = df2['Country'],

locationmode = "country names",

z = df2['Power Consumption KWH'],

text = df2['Country'],

colorbar = {'title' : 'Power Consumption'},

) >>> layout = dict(title = 'Power Consumption',geo = dict(showframe = False,projection = {'type':'mercator'})

) >>> chmap = go.Figure(data = [data],layout = layout)

>>> iplot(chmap)

For more detailed information on Choropleth maps, check the official documentation here. Refer to the notebook for code here.