{ "cells": [ { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "# Interactive maps\n", "\n", "In this tutorial we will learn how to publish data from Python on interactive [leaflet.js](http://leafletjs.com/) maps. \n", "\n", "JavaScript (JS) is a programming language for adding interactive content (such a zoomamble maps!) on webpages. [Leaflet](http://leafletjs.com/) is a popular JavaScript library for creating interactive maps for webpages ([OpenLayers](https://openlayers.org/) is another JavaScript library for the same purpose). \n", "\n", "Here, will mainly focus on [Folium](https://python-visualization.github.io/folium/) - a Python library that makes it easy to convert data from (Geo)DataFrames into interactive Leaflet maps.\n", "\n", "
\n", "\n", "**Explore also...**\n", " \n", "Other interesting libraries for creating interactive visualizations from spatial data:\n", " \n", "- [mapboxgl](https://github.com/mapbox/mapboxgl-jupyter)\n", "- [Bokeh](https://docs.bokeh.org/en/latest/)\n", "- [Geoviews](http://geoviews.org/)\n", "- [plotly express](https://plotly.com/python/maps/)\n", "\n", "
\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Folium\n", "\n", "\n", "[Folium](https://github.com/python-visualization/folium) is a Python library that makes\n", "it possible visualize data on an interactive Leaflet map.\n", "\n", "**Resources:**\n", "\n", "- [Folium Documentation](https://python-visualization.github.io/folium/)\n", "- [Example Gallery](https://nbviewer.jupyter.org/github/python-visualization/folium/tree/master/examples/)\n", "- [Folium Quickstart](https://python-visualization.github.io/folium/quickstart.html)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating a simple interactive web-map\n", "\n", "Import folium and other useful packages:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import folium" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from pyproj import crs\n", "import geopandas as gpd\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will start by creating a simple interactive web-map without any data on it. We just visualize OpenStreetMap on a specific location of the world.\n", "\n", "First thing that we need to do is to create [a Map instance](https://python-visualization.github.io/folium/modules.html#folium.folium.Map) and define a location for zooming in the data: " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "deletable": true, "editable": true }, "outputs": [], "source": [ "# Create a Map instance\n", "m = folium.Map(location=[60.25, 24.8], zoom_start=10, control_scale=True)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "The first parameter ``location`` takes a pair of lat, lon values as list as an input which will determine where the map will be positioned when user opens up the map. ``zoom_start`` -parameter adjusts the default zoom-level for the map (the higher the number the closer the zoom is). ``control_scale`` defines if map should have a scalebar or not." ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Let's see what our map looks like: " ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "We can also save the map as a html file:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "outfp = \"base_map.html\"\n", "m.save(outfp)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "\n", "You should now see a html file in your working directory. You can open the file in a web-browser in order to see the map, or in a text editor in order to see the source definition.\n", "\n", "\n", "Let's create another map with different settings (location, bacground map, zoom levels etc). See documentation of the [Map() object](https://python-visualization.github.io/folium/modules.html#folium.folium.Map) for all avaiable options.\n", " \n", "``tiles`` -parameter is used for changing the background map provider and map style (see the [documentation](https://python-visualization.github.io/folium/modules.html#folium.folium.Map) for all in-built options).\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Let's change the basemap style to 'Stamen Toner'\n", "m = folium.Map(location=[40.730610, -73.935242], tiles='Stamen Toner',\n", " zoom_start=12, control_scale=True, prefer_canvas=True)\n", "\n", "m" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Adding layers to the map\n", "\n", "Let's first have a look how we can add a simple [marker](https://python-visualization.github.io/folium/modules.html?highlight=marker#folium.map.Marker) on the webmap:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a Map instance\n", "m = folium.Map(location=[60.20, 24.96],\n", " zoom_start=12, control_scale=True)\n", "\n", "# Add marker\n", "# Run: help(folium.Icon) for more info about icons\n", "folium.Marker(\n", " location=[60.20426, 24.96179],\n", " popup='Kumpula Campus',\n", " icon=folium.Icon(color='green', icon='ok-sign'),\n", ").add_to(m)\n", "\n", "#Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "As mentioned, Folium combines the strenghts of data manipulation in Python with the mapping capabilities of Leaflet.js. Eventually, we would like to include the plotting of interactive maps as the last part of our data analysis workflow. \n", "\n", "Let's see how we can plot data from a geodataframe using folium.\n", "\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
addressidgeometry
0Kampinkuja 1, 00100 Helsinki, Finland1001POINT (24.93017 60.16837)
1Kaivokatu 8, 00101 Helsinki, Finland1002POINT (24.94189 60.16987)
2Hermanstads strandsväg 1, 00580 Helsingfors, F...1003POINT (24.97740 60.18736)
3Itäväylä, 00900 Helsinki, Finland1004POINT (25.09196 60.21448)
4Tyynenmerenkatu 9, 00220 Helsinki, Finland1005POINT (24.92148 60.15658)
\n", "
" ], "text/plain": [ " address id \\\n", "0 Kampinkuja 1, 00100 Helsinki, Finland 1001 \n", "1 Kaivokatu 8, 00101 Helsinki, Finland 1002 \n", "2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 \n", "3 Itäväylä, 00900 Helsinki, Finland 1004 \n", "4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 \n", "\n", " geometry \n", "0 POINT (24.93017 60.16837) \n", "1 POINT (24.94189 60.16987) \n", "2 POINT (24.97740 60.18736) \n", "3 POINT (25.09196 60.21448) \n", "4 POINT (24.92148 60.15658) " ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# File path\n", "points_fp = r\"data/addresses.shp\"\n", "\n", "# Read the data\n", "points = gpd.read_file(points_fp)\n", "\n", "#Check input data\n", "points.head()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
addressidgeometry
0Kampinkuja 1, 00100 Helsinki, Finland1001POINT (24.93017 60.16837)
1Kaivokatu 8, 00101 Helsinki, Finland1002POINT (24.94189 60.16987)
2Hermanstads strandsväg 1, 00580 Helsingfors, F...1003POINT (24.97740 60.18736)
3Itäväylä, 00900 Helsinki, Finland1004POINT (25.09196 60.21448)
4Tyynenmerenkatu 9, 00220 Helsinki, Finland1005POINT (24.92148 60.15658)
\n", "
" ], "text/plain": [ " address id \\\n", "0 Kampinkuja 1, 00100 Helsinki, Finland 1001 \n", "1 Kaivokatu 8, 00101 Helsinki, Finland 1002 \n", "2 Hermanstads strandsväg 1, 00580 Helsingfors, F... 1003 \n", "3 Itäväylä, 00900 Helsinki, Finland 1004 \n", "4 Tyynenmerenkatu 9, 00220 Helsinki, Finland 1005 \n", "\n", " geometry \n", "0 POINT (24.93017 60.16837) \n", "1 POINT (24.94189 60.16987) \n", "2 POINT (24.97740 60.18736) \n", "3 POINT (25.09196 60.21448) \n", "4 POINT (24.92148 60.15658) " ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "points.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- conver the points to GeoJSON features using folium:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "# Convert points to GeoJSON\n", "points_gjson = folium.features.GeoJson(points, name=\"Public transport stations\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# Check the GeoJSON features\n", "#points_gjson.data.get('features')" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Now we have our population data stored as GeoJSON format which basically contains the\n", "data as text in a similar way that it would be written in the ``.geojson`` -file." ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Add the points onto the Helsinki basemap:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a Map instance\n", "m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=11, control_scale=True)\n", "\n", "# Add points to the map instance\n", "points_gjson.add_to(m)\n", "\n", "# Alternative syntax for adding points to the map instance\n", "#m.add_child(points_gjson)\n", "\n", "#Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Layer control\n", "\n", "We can also add a `LayerControl` object on our map, which allows the user to control which map layers are visible. See the [documentation](http://python-visualization.github.io/folium/docs-v0.5.0/modules.html#folium.map.LayerControl) for available parameters (you can e.g. change the position of the layer control icon)." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a layer control object and add it to our map instance\n", "folium.LayerControl().add_to(m)\n", "\n", "#Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Heatmap\n", "\n", "[Folium plugins](https://python-visualization.github.io/folium/plugins.html) allow us to use popular tools available in leaflet. One of these plugins is [HeatMap](https://python-visualization.github.io/folium/plugins.html#folium.plugins.HeatMap), which creates a heatmap layer from input points. \n", "\n", "Let's visualize a heatmap of the public transport stations in Helsinki using the addresses input data. [folium.plugins.HeatMap](https://python-visualization.github.io/folium/plugins.html#folium.plugins.HeatMap) requires a list of points, or a numpy array as input, so we need to first manipulate the data a bit:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "deletable": true, "editable": true }, "outputs": [], "source": [ "# Get x and y coordinates for each point\n", "points[\"x\"] = points[\"geometry\"].apply(lambda geom: geom.x)\n", "points[\"y\"] = points[\"geometry\"].apply(lambda geom: geom.y)\n", "\n", "# Create a list of coordinate pairs\n", "locations = list(zip(points[\"y\"], points[\"x\"]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Check the data:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/plain": [ "[(60.1683731, 24.9301701),\n", " (60.1698665, 24.9418933),\n", " (60.18735880000001, 24.9774004),\n", " (60.21448089999999, 25.0919641),\n", " (60.1565781, 24.9214846),\n", " (60.23489060000001, 25.0816923),\n", " (60.2033879, 25.042239),\n", " (60.2753891, 25.035855),\n", " (60.2633799, 25.0291078),\n", " (60.22243630000001, 24.8718598),\n", " (60.1711874, 24.94251),\n", " (60.2306474, 24.8840504),\n", " (60.240163, 24.877383),\n", " (60.22163339999999, 24.9483202),\n", " (60.25149829999999, 25.0125655),\n", " (60.2177823, 24.893153),\n", " (60.2485471, 24.86186),\n", " (60.2291135, 24.9670533),\n", " (60.1986856, 24.9334051),\n", " (60.22401389999999, 24.8609335),\n", " (60.2436961, 24.9934979),\n", " (60.24444239999999, 25.040583),\n", " (60.20966609999999, 25.0778094),\n", " (60.20751019999999, 25.1424936),\n", " (60.225599, 25.0756547),\n", " (60.2382054, 25.1080054),\n", " (60.18789030000001, 24.9609122),\n", " (60.19413939999999, 25.0291263),\n", " (60.18837519999999, 25.0068399),\n", " (60.1793862, 24.9494874),\n", " (60.1694809, 24.9337569),\n", " (60.16500139999999, 24.9250072),\n", " (60.159069, 24.9214046),\n", " (60.1719108, 24.9468514),\n", " (60.20548979999999, 25.1204966)]" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "locations" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from folium.plugins import HeatMap\n", "\n", "# Create a Map instance\n", "m = folium.Map(location=[60.25, 24.8], tiles = 'stamentoner', zoom_start=10, control_scale=True)\n", "\n", "# Add heatmap to map instance\n", "# Available parameters: HeatMap(data, name=None, min_opacity=0.5, max_zoom=18, max_val=1.0, radius=25, blur=15, gradient=None, overlay=True, control=True, show=True)\n", "HeatMap(locations).add_to(m)\n", "\n", "# Alternative syntax:\n", "#m.add_child(HeatMap(points_array, radius=15))\n", "\n", "# Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": { "editable": true }, "source": [ "### Clustered point map\n", "\n", "Let's visualize the address points (locations of transport stations in Helsinki) on top of the choropleth map using clustered markers using folium's [MarkerCluster](https://python-visualization.github.io/folium/plugins.html?highlight=marker%20cluster#folium.plugins.MarkerCluster) class." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "editable": true }, "outputs": [], "source": [ "from folium.plugins import MarkerCluster" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# Create a Map instance\n", "m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=11, control_scale=True)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# Following this example: https://github.com/python-visualization/folium/blob/master/examples/MarkerCluster.ipynb\n", "\n", "# Get x and y coordinates for each point\n", "points[\"x\"] = points[\"geometry\"].apply(lambda geom: geom.x)\n", "points[\"y\"] = points[\"geometry\"].apply(lambda geom: geom.y)\n", "\n", "# Create a list of coordinate pairs\n", "locations = list(zip(points[\"y\"], points[\"x\"]))" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a folium marker cluster\n", "marker_cluster = MarkerCluster(locations)\n", "\n", "# Add marker cluster to map\n", "marker_cluster.add_to(m)\n", "\n", "# Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "### Choropleth map" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Next, let's check how we can overlay a population map on top of a basemap using [folium's choropleth method](http://python-visualization.github.io/folium/docs-v0.5.0/modules.html#folium.folium.Map.choropleth). This method is able to read the geometries and attributes directly from a geodataframe. \n", "This example is modified from the [Folium quicksart](https://python-visualization.github.io/folium/quickstart.html#Choropleth-maps).\n", "\n", "- First read in the population grid from HSY wfs like we did in [lesson 3](https://automating-gis-processes.github.io/site/notebooks/L3/spatial-join.html):" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
geometryindexasukkaitaasvaljyysika0_9ika10_19ika20_29ika30_39ika40_49ika50_59ika60_69ika70_79ika_yli80
0MULTIPOLYGON Z (((25476499.999 6674248.999 0.0...3342108451123672617864
1MULTIPOLYGON Z (((25476749.997 6674498.998 0.0...3503273353524526240262590
2MULTIPOLYGON Z (((25476999.994 6675749.004 0.0...36602393446242445333025102
3MULTIPOLYGON Z (((25476999.994 6675499.004 0.0...366120230523713364311433
4MULTIPOLYGON Z (((25476999.994 6675249.005 0.0...366226130643236643420632
\n", "
" ], "text/plain": [ " geometry index asukkaita \\\n", "0 MULTIPOLYGON Z (((25476499.999 6674248.999 0.0... 3342 108 \n", "1 MULTIPOLYGON Z (((25476749.997 6674498.998 0.0... 3503 273 \n", "2 MULTIPOLYGON Z (((25476999.994 6675749.004 0.0... 3660 239 \n", "3 MULTIPOLYGON Z (((25476999.994 6675499.004 0.0... 3661 202 \n", "4 MULTIPOLYGON Z (((25476999.994 6675249.005 0.0... 3662 261 \n", "\n", " asvaljyys ika0_9 ika10_19 ika20_29 ika30_39 ika40_49 ika50_59 \\\n", "0 45 11 23 6 7 26 17 \n", "1 35 35 24 52 62 40 26 \n", "2 34 46 24 24 45 33 30 \n", "3 30 52 37 13 36 43 11 \n", "4 30 64 32 36 64 34 20 \n", "\n", " ika60_69 ika70_79 ika_yli80 \n", "0 8 6 4 \n", "1 25 9 0 \n", "2 25 10 2 \n", "3 4 3 3 \n", "4 6 3 2 " ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import geopandas as gpd\n", "from pyproj import CRS\n", "import requests\n", "import geojson\n", "\n", "# Specify the url for web feature service\n", "url = 'https://kartta.hsy.fi/geoserver/wfs'\n", "\n", "# Specify parameters (read data in json format).\n", "# Available feature types in this particular data source: http://geo.stat.fi/geoserver/vaestoruutu/wfs?service=wfs&version=2.0.0&request=describeFeatureType\n", "params = dict(service='WFS',\n", " version='2.0.0',\n", " request='GetFeature',\n", " typeName='asuminen_ja_maankaytto:Vaestotietoruudukko_2018',\n", " outputFormat='json')\n", "\n", "# Fetch data from WFS using requests\n", "r = requests.get(url, params=params)\n", "\n", "# Create GeoDataFrame from geojson\n", "data = gpd.GeoDataFrame.from_features(geojson.loads(r.content))\n", "\n", "# Check the data\n", "data.head()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [], "source": [ "from pyproj import CRS\n", "# Define crs\n", "data.crs = CRS.from_epsg(3879)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Re-project layer into WGS 84 (epsg: 4326)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "epsg:4326\n" ] } ], "source": [ "# Re-project to WGS84\n", "data = data.to_crs(epsg=4326)\n", "\n", "# Check layer crs definition\n", "print(data.crs)" ] }, { "cell_type": "markdown", "metadata": { "deletable": true, "editable": true }, "source": [ "Rename columns" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "# Change the name of a column\n", "data = data.rename(columns={'asukkaita': 'pop18'})" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "# Create a Geo-id which is needed by the Folium (it needs to have a unique identifier for each row)\n", "data['geoid'] = data.index.astype(str)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
geoidpop18geometry
00108MULTIPOLYGON Z (((24.57654 60.18042 0.00000, 2...
11273MULTIPOLYGON Z (((24.58102 60.18267 0.00000, 2...
22239MULTIPOLYGON Z (((24.58538 60.19391 0.00000, 2...
33202MULTIPOLYGON Z (((24.58541 60.19166 0.00000, 2...
44261MULTIPOLYGON Z (((24.58544 60.18942 0.00000, 2...
\n", "
" ], "text/plain": [ " geoid pop18 geometry\n", "0 0 108 MULTIPOLYGON Z (((24.57654 60.18042 0.00000, 2...\n", "1 1 273 MULTIPOLYGON Z (((24.58102 60.18267 0.00000, 2...\n", "2 2 239 MULTIPOLYGON Z (((24.58538 60.19391 0.00000, 2...\n", "3 3 202 MULTIPOLYGON Z (((24.58541 60.19166 0.00000, 2...\n", "4 4 261 MULTIPOLYGON Z (((24.58544 60.18942 0.00000, 2..." ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Select only needed columns\n", "data = data[['geoid', 'pop18', 'geometry']]\n", "\n", "# Convert to geojson (not needed for the simple coropleth map!)\n", "#pop_json = data.to_json()\n", "\n", "#check data\n", "data.head()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create an interactive choropleth map from the population grid:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false, "deletable": true, "editable": true, "jupyter": { "outputs_hidden": false } }, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a Map instance\n", "m = folium.Map(location=[60.25, 24.8], tiles = 'cartodbpositron', zoom_start=10, control_scale=True)\n", "\n", "# Plot a choropleth map\n", "# Notice: 'geoid' column that we created earlier needs to be assigned always as the first column\n", "folium.Choropleth(\n", " geo_data=data,\n", " name='Population in 2018',\n", " data=data,\n", " columns=['geoid', 'pop18'],\n", " key_on='feature.id',\n", " fill_color='YlOrRd',\n", " fill_opacity=0.7,\n", " line_opacity=0.2,\n", " line_color='white', \n", " line_weight=0,\n", " highlight=False, \n", " smooth_factor=1.0,\n", " #threshold_scale=[100, 250, 500, 1000, 2000],\n", " legend_name= 'Population in Helsinki').add_to(m)\n", "\n", "#Show map\n", "m" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tooltips\n", "\n", "It is possible to add different kinds of pop-up messages and tooltips to the map. Here, it would be nice to see the population of each grid cell when you hover the mouse over the map. Unfortunately this functionality is not apparently implemented implemented in the Choropleth method we used before. \n", "\n", "Add tooltips, we can add tooltips to our map when plotting the polygons as GeoJson objects using the `GeoJsonTooltip` feature. (following examples from [here](http://nbviewer.jupyter.org/gist/jtbaker/57a37a14b90feeab7c67a687c398142c?flush_cache=true) and [here](https://nbviewer.jupyter.org/github/jtbaker/folium/blob/geojsonmarker/examples/GeoJsonMarkersandTooltips.ipynb))\n", "\n", "For a quick workaround, we plot the polygons on top of the coropleth map as a transparent layer, and add the tooltip to these objects. *Note: this is not an optimal solution as now the polygon geometry get's stored twice in the output!*" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
Make this Notebook Trusted to load map: File -> Trust Notebook
" ], "text/plain": [ "" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Convert points to GeoJson\n", "folium.features.GeoJson(data, \n", " name='Labels',\n", " style_function=lambda x: {'color':'transparent','fillColor':'transparent','weight':0},\n", " tooltip=folium.features.GeoJsonTooltip(fields=['pop18'],\n", " aliases = ['Population'],\n", " labels=True,\n", " sticky=False\n", " )\n", " ).add_to(m)\n", "\n", "m" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Rember that you can also save the output as an html file: " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "outfp = \"choropleth_map.html\"\n", "m.save(outfp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Extra: check out plotly express for an alternative way of plotting an interactive Choropleth map [in here](https://plotly.com/python/mapbox-county-choropleth/)." ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }