Search⌘ K
AI Features

Geographical Plotting

Explore how to create interactive geographical visualizations using Plotly in Python. Understand how to work with choropleth maps, handle geographic datasets, and customize visual elements for US and world maps. Gain practical skills in building text data for hover features and applying various color scales for effective data presentation.

We'll cover the following...

Geographical plotting is usually challenging because of the various formats in the data sets. Plotly provides a way to plot geographical data interactively using its choropleth type.

Note: Matplotlib also provides the extension basemap for static geographical plotting.

Write the following code and review it line by line using inline comments.

The following code will show us how we can create geographical plots using Plotly:

Python
# Let's do the required import for geographical plotting!
import plotly.graph_objs as go
# First, we build the data dictionary "trc" using the dict method.
trc = dict(
type = 'choropleth', # type of plot
locations = ['AZ','CA','VT'], # list of state abbreviations
locationmode = 'USA-states', # This lets ploty know we are creating out map at the national level
colorscale= 'Viridis', # setting a color scale
text= ['Arizona','California','Vermont'], # another key, text that hover over each location
z=[10,20,30], # the actual value that will be shown on the color scale
colorbar = {'title':'Colorbar Title'} # Passing what the color bar title will be
)
#Let's create a layout variable, a nested dict object
lyt = dict(geo = dict(scope ='usa'))
# Passing data and layout to the go.Figure
map = go.Figure(data = [trc], layout = lyt)
# Passing map to iplot for plotting
iplot(map)

The following plot is generated by the code given above:

US map choropleth

Now let’s see an example with some real data on exports. The datasets are available on the Plotly GitHub page. We can pass a link to the dataset and read it directly into a DataFrame. A copy of the dataset (with a few small modifications) is also included in the folder, in case you can’t access the internet. We can read the data from these downloaded .csv files. When using the included .csv files, you don’t need to do the steps to add new columns.

Python
df = pd.read_csv('2011_us_ag_exports_mod.csv')
print(df.head())

If we look at the DataFrame, we have individual columns for the export of the given products (beef, dairy, veggies, and so on) to each state.

We have to build our text column most of the time, so let’s create a new column that combines this information. Then, we can pass it to the text key that will hover on the plot.

We need to convert the column datatype from float to string first.

Python
for col in df.columns:
df[col] = df[col].astype(str)

Let’s create the data dictionary with some extra marker and color bar arguments. We’ll then create a layout and get our geographical plot.

Python
# The data dict
data = dict(type='choropleth',
colorscale = 'Earth', # random selection - try a different one from the list given below
locations = df['code'], # passing column with state codes
locationmode = 'USA-states',
z = df['total exports'], # What the color nar will represent
text = df['text'], # Newly generated column to hover
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, # we want actual lakes on the map
lakecolor = 'rgb(85,173,240)') # blue for lakes
)
# Passing data and layout to the go.Figure
choromap = go.Figure(data = [data], layout = layout)
# Passing map to iplot for plotting
iplot(choromap)

The following plot is generated by the code given above:

The following are some possible colorscale values you can try: ['Greys', 'YlGnBu', 'Greens', 'YlOrRd', 'Bluered', 'RdBu', 'Reds', 'Blues', 'Picnic', 'Rainbow', 'Portland', 'Jet', 'Hot', 'Blackbody', 'Earth', 'Electric', 'Viridis', 'Cividis'].

Note: These values are updated frequently. Please consult the official documentation of Plotly to see the updated list of colorscale values.

World choropleth map

Now let’s see an example with a world map.

Python
# Let's read world GDP data from plotly datasts
gdp = pd.read_csv('2014_world_gdp.csv')
#gdp.to_csv('2014_world_gdp.csv') # used to save the file for offline use, you can load and work with it!
print(gdp.head())

Let’s use iplot to print the map.

Python
# Data dictionary
data = dict(
type = 'choropleth',
locations = gdp['CODE'], # This is country code now
z = gdp['GDP (BILLIONS)'],
text = gdp['COUNTRY'], # Country name
colorbar = {'title' : 'GDP Billions US'},
)
# Layout
layout = dict(
title = '2014 Global GDP',
geo = dict(
showframe = False, #
projection = {'type':'mercator'}#'mollweide'}#"natural earth"}
)
)
#Finally plotting
choromap = go.Figure(data = [data],layout = layout)
iplot(choromap)

The following plot is generated by the code given above:

To see everything in action, run the app given below.

Please login to launch live app!