Map Visualization with Folium
What is 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.
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)
folium.Map(location=[41,29],tiles="Stamen Toner",
width="%100",
height="%100")
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
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
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
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
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()
data_koordinat=pd.read_excel("ilcelere-gore-abone-sayilari.xlsx",sheet_name="Koordinatlar")
data_koordinat.head()
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()
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
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
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
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
m = folium.Map(tiles="Cartodbdark_matter",width="%100",weight="%100")GeoJson(text,).add_to(m)m
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 filenufus.head()
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
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()
airbnb_data.isnull().sum().to_frame() #let’s look at missing values
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
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
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()
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
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