Categories:

Generating Maps with Python

Generating Maps with Python is very easy. Maps are generally in the geospatial data. In order to visualize geospatial data, Folium was made. While other libraries, such as Plotly, are able to view geospatial data, they can capture the number of API calls in a given time frame.

We also use pandas and matplotlib in the following datasets

Introduction to Folium

Folium is a popular library from Python, which allows you to generate various types of maps. This library is very useful for dashboard construction since the Folium findings are interactive.

It includes a variety of built-in OpenStreetMap, Mapbox and Stamen tilesets, and supports personalized Mapbox or Cloudmade API keys tilesets. Both GeoJSON and TopoJSON overlays are assisted by Folium.

Folium is not available by default. So, we first need to install it before we are able to import it. Install it from here https://python-visualization.github.io/folium/installing.html

We will be using Jupyter Notebook

Simple Folium Map

import folium

# define the world map
world_map = folium.Map()

# display world map
world_map

Folium Map with Zoom Level

# define the world map centered with a zoom level
world_map = folium.Map(location=[27.130, 85.35], zoom_start=8)

# display world map
world_map

Stamen Toner Maps

high-contrast B+W (black and white) maps

# create a Stamen Toner map of the world centered around Nepal
world_map = folium.Map(location=[27.130, 85.35], zoom_start=4, tiles='Stamen Toner')

# display map
world_map

Stamen Terrain Maps

Feature hill shading and natural vegetation colors / advanced labeling and linework generalization of dual-carriageway roads.

# create a Stamen Toner map of the world centered around Canada
world_map = folium.Map(location=[27.130, 85.35], zoom_start=4, tiles='Stamen Terrain')

# display map
world_map

Maps with Markers

Let’s download and import the data on police department incidents using pandas read_csv() method.

Download the dataset and read it into a pandas dataframe:

df_incidents = pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Police_Department_Incidents_-_Previous_Year__2016_.csv')

print('Dataset downloaded and read into a pandas dataframe!')

# instantiate a feature group for the incidents in the dataframe
incidents = folium.map.FeatureGroup()

# loop through the 100 crimes and add each to the incidents feature group
for lat, lng, in zip(df_incidents.Y, df_incidents.X):
    incidents.add_child(
        folium.features.CircleMarker(
            [lat, lng],
            radius=5, # define how big you want the circle markers to be
            color='yellow',
            fill=True,
            fill_color='blue',
            fill_opacity=0.6
        )
    )

# add pop-up text to each marker on the map
latitudes = list(df_incidents.Y)
longitudes = list(df_incidents.X)
labels = list(df_incidents.Category)

for lat, lng, label in zip(latitudes, longitudes, labels):
    folium.Marker([lat, lng], popup=label).add_to(sanfran_map)    
    
# add incidents to map
sanfran_map.add_child(incidents)

Choropleth Maps

A Choropleth map is a thematic map in which areas are shaded or patterned in proportion to the measurement of the statistical variable shown on the map, such as population density or per capita income.

We are using Canada Immigrants Data set for this purpose and cleanup the data before loading into map.

df_can = pd.read_excel('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/Canada.xlsx',
                     sheet_name='Canada by Citizenship',
                     skiprows=range(20),
                     skipfooter=2)

print('Data downloaded and read into a dataframe!')

# clean up the dataset to remove unnecessary columns (eg. REG) 
df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True)

# let's rename the columns so that they make sense
df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent','RegName':'Region'}, inplace=True)

# for sake of consistency, let's also make all column labels of type string
df_can.columns = list(map(str, df_can.columns))

# add total column
df_can['Total'] = df_can.sum(axis=1)

# years that we will be using in this lesson - useful for plotting later on
years = list(map(str, range(1980, 2014)))
print ('data dimensions:', df_can.shape)

# download countries geojson file
!wget --quiet https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/world_countries.json
    
print('GeoJSON file downloaded!')

world_geo = r'world_countries.json' # geojson file

# create a plain world map
world_map = folium.Map(location=[0, 0], zoom_start=2)

# generate choropleth map using the total immigration of each country to Canada from 1980 to 2013
world_map.choropleth(
    geo_data=world_geo,
    data=df_can,
    columns=['Country', 'Total'],
    key_on='feature.properties.name',
    fill_color='YlOrRd', 
    fill_opacity=0.7, 
    line_opacity=0.2,
    legend_name='Immigration to Canada'
)

# display map
world_map