Map Visualization with Folium
Tags: Maps, Visualization, Folium, Python

Map Visualization with Folium

Folium is a library that uses JavaScript leaflet.js module in the background and it enables interactive map visualizations in Python. Now let’s examine some features in Folium.

1. Map() and Tiles

Firstly, let’s take the necessary steps to use the Folium library.

pip install folium

#conda install -c conda-forge folium

import folium

We use the Map() function to create a map. For this, we need to give latitude and longitude information to the function. For example, let us enter the approximate latitude and longitude of Istanbul.

folium.Map(location=[41,29])

Let’s look at the output without any parameters.

Figure 1. Folium-Output-1

By default, “tiles” appears as ”OpenStreetMap” in the Map() function.This parameter allows us to change the style of the map. We can change this to Stamen Toner, CartoDB positron, Cartodb dark_matter, Stamen Watercolor or Stamen Terrain. we also adjust the size with the width and height parameters, and zoom_start lets you zoom in.

folium.Map(location=[41,29],

tiles="Stamen Watercolor",

width="%100",

height="%100",

zoom_start=10)

Figure 2. Folium-Output-2

folium.Map(location=[41,29],tiles="Stamen Toner",

width="%100",

height="%100")

Figure 3. Folium-Output-3

2. Circle(),CircleMarker() ve Marker()

We can use the Circle() function to circle the coordinates. Let’s look at the output by entering parameters such as radius and color.

m = folium.Map(location=[41,29],tiles="Stamen Toner",

width="%100",

height="%100",

zoom_start=10) folium.Circle(

radius=5000,

location=[41,29],

color='crimson',

fill=False,).add_to(m)

m

Figure 4. Folium-Output-4

Another way to do this is to use the CircleMarker() function.

m = folium.Map(location=[41,29],tiles="Stamen Toner",width="%100",height="%100") folium.CircleMarker(location=(41,29),radius=100, fill_color='red').add_to(m)

m

Figure 5. Folium-Output-5

Now let’s use the coordinates of Sakarya as an example and use the Marker() function to mark the location of the coordinates. Let’s set the location name by using the popup parameter.

m = folium.Map(location=[40.75834,30.38001])

folium.Marker(location=[40.75834,30.38001], popup = 'Sakarya').add_to(m) folium.CircleMarker(location=(40.75834,30.38001),radius=100, fill_color='blue').add_to(m) m

Figure 6. Folium-Output-6

3. MiniMap()

Let’s call plugins from Folium firstly. In order to create a minimap, use the MiniMap() function.

from folium import plugins

m = folium.Map(location=(42, 29), zoom_start=5) minimap = plugins.MiniMap()

m.add_child(minimap)

m

Figure 7. Folium-Output-7

4. MarkerCluster()

For this example, I used the data “number of natural gas subscribers by counties” in the IBB Open Data Portal. This data consists of county names and subscriber count data.Since we need coordinates of Istanbul districts, you can pull the coordinate information from Google Maps or get it from platforms like GitHub. Now let’s start loading data in Excel format. For that, we need the Pandas library. After loading the data, let’s observe the first 5 values.

İmport pandas as pd

data_abone=pd.read_excel("ilcelere-gore-abone- sayilari.xlsx",sheet_name="İlçe Abone Sayı")

data_abone.head()

Figure 8. Folium-Output-8

data_koordinat=pd.read_excel("ilcelere-gore-abone-sayilari.xlsx",sheet_name="Koordinatlar")

data_koordinat.head()

Figure 9. Folium-Output-9

Since there are columns with the same name, we can combine this data by using the merge() function in Pandas.

data=pd.merge(data_abone,data_koordinat)

df=data.copy()

df.head()

Figure 10. Folium-Output-10

The MarkerCluster() function is included in Plugins. Let’s give the location information as a parameter.

m = folium.Map([42 ,29], zoom_start=5,width="%100",height="%100")

location=df[["Enlem","Boylam"]] plugins.MarkerCluster(location).add_to(m) m

Figure 11. Folium-Output-11

Figure 12. Folium-Output-12

5. HeatMap()

For heatmap, we can use heatmap() in Plugins. For that, we need to give the data in the appropriate format. Now let’s take the necessary steps and look at our output.

df.Enlem=df.Enlem.astype(float)

df.Boylam=df.Boylam.astype(float)

heat_df=df[["Enlem","Boylam"]]

heat_data=list(zip(df.Enlem, df.Boylam))

folium.plugins.HeatMap(heat_data).add_to(m)

m

Figure 13. Folium-Output-13

6. GeoJson

GeoJson in the Folium helps us border the coordinates we want. We need a json file with coordinates to draw the boundaries. You can find it from the platforms like Github or you can draw these boundaries yourself and create a json file by using geojson.io. For this example, let’s use the borders of Turkey except Cyprus.

from folium import GeoJson

geo=r"tr-cities.json"

file = open(geo, encoding="utf8")

text = file.read() m = folium.Map(width="%100",weight="%100") GeoJson(text).add_to(m)

m

Figure 14. Folium-Output-14

m = folium.Map(tiles="Stamen Toner") GeoJson(text,

style_function=lambda feature: {

'fillColor': '#adff2f',

'color':None,

'weight': 1,

'dashArray': '4, 4'

}).add_to(m)

m

Figure 15. Folium-Output-15

m = folium.Map(tiles="Cartodbdark_matter",width="%100",weight="%100") GeoJson(text,).add_to(m) m

Figure 16. Folium-Output-16

7. Choropleth()

For this example, I am going to use the data “population number according to place of birth” on the Turkish Statistical Institute’s website. Now let’s load the data and do the necessary cleaning.

nufus=pd.read_excel(r"pivot.xls") nufus.drop("Unnamed: 2",axis=1,inplace=True) nufus.drop(nufus[nufus["Sehir"]=="Yurtdışı"].index,inplace=True) nufus.drop(nufus[nufus["Sehir"]=="Bilinmeyen"].index,inplace=True) nufus.loc[nufus["Sehir"]=="Afyonkarahisar","Sehir"]="Afyon" #I changed the name to Afyon as in the text file nufus.head()

Figure 17. Folium-Output-17

Now let’s try to color the map by population.For this we can use the Choropleth () function. Here we can think of the parameter as key_on as a “primary key” i.e. an unique token for each property. It may be useful to open the text file to understand exactly what we should write.

m = folium.Map([42 ,29],tiles="Cartodb Positron",

zoom_start=5,

width="%100",

height="%100")

folium.Choropleth(

geo_data=text,

data=nufus,

columns=['Sehir', 'Nufus'],

legend_name='Dogum Yerine Gore Nufus (2019)',

key_on='feature.properties.name'

#‘feature.id’ or ‘feature.properties.statename’

).add_to(m) m

Figure 18. Folium-Output-18

Implementation with Istanbul Airbnb Data

Let’s upload our data and examine it briefly, as we did before.

airbnb_data=pd.read_csv("airbnbIstanbul.csv") airbnb_data.head()

Figure 19. Folium-Output-19

airbnb_data.isnull().sum().to_frame() #let’s look at missing values

Figure 20. Folium-Output-20

The price, latitude and longitude data show no missing value. Now let’s map their accommodation places by using each coordinate data. For this we can use the MarkerCluster() function.

m = folium.Map([42 ,29], zoom_start=5,width="%100",height="%100")

locations = list(zip(airbnb_data.latitude, airbnb_data.longitude))

cluster = plugins.MarkerCluster(locations=locations,

popups=airbnb_data["neighbourhood"].tolist())

m.add_child(cluster)

m

Figure 21. Folium-Output-21

Now let’s do the same process using CircleMaker().

m = folium.Map(location=[41,29],width="%100",height="%100")

for i in range(len(locations)):

folium.CircleMarker(location=locations[i],radius=1).add_to(m)

m

Figure 22. Folium-Output-22

Now our goal is to color the accommodation according to the prices. We need a colormap for that. We will give different colors for certain price ranges. To do this, let’s first assign the minimum and maximum prices to different variables.

airbnb=airbnb_data[["latitude","longitude","price"]] min_price=airbnb_data["price"].min() max_price=airbnb_data["price"].max() airbnb["price"].describe().to_frame()

Figure 23. Folium-Output-23

I created the colormap using cartil values. You can create it with different values and different colors.Then we can create our map using the Circle() function.

m = folium.Map(location=[41,29],width="%100",height="%100")

colormap = cm.StepColormap(colors=['green','yellow','orange','red'] ,#renkler

index=[min_price,105,190,327,max_price], #eşik değerler

vmin= min_price,

vmax=max_price) for loc, p in zip(zip(airbnb["latitude"],airbnb["longitude"]),airbnb["price"]):

folium.Circle(

location=loc,

radius=2, #yarıçap

fill=True,

color=colormap(p) ).add_to(m) m

Figure 24. Folium-Output-24

Now, finally, let’s create a heatmap.

heat_data = airbnb.groupby(["latitude","longitude"]['price'].mean()

.reset_index().values.tolist()

folium.plugins.HeatMap(heat_data).add_to(m)

m

Figure 25. Folium-Output-25

In order to access the data sets I used in this article:

Population number data by place of birth: Türkiye İstatistik Kurumu Web Sitesi

İstanbul Airbnb data: Kaggle İstanbul Airbnb Verisi

Istanbul natural gas subscriber count data: İBB Açık Veri Portalı

All codes : https://github.com/ferhatmetin34/Map-Visualization-with-Folium

In order to access the resources I used:

https://nbviewer.jupyter.org/github/pythonvisualization/folium/tree/master

https://pypi.org/project/folium