SoFunction
Updated on 2024-11-19

A beginner's guide to folium, the Python mapping tool.

I. Introduction

Want to create beautiful maps with Python? Want the freedom to set various parameters on the map? Want a flexible interactive experience? Here's a Python toolkit for you:folium

folium builds on the data application capabilities of the Python ecosystem and the mapping capabilities of libraries to manipulate data in Python and then visualize it in Leaflet maps via folium.

folium compared to the domestic Baidu pyecharts more flexible, can customize the drawing area, and more diverse forms of presentation.

Attachment:official documentofficial exampleThis article notebookFull code and data

II. Installation methods

Just follow the official tutorial, or if you have conda installed, you can directly

conda install -c conda-forge folium

If you don't have it installed, use the

python3 -m pip install folium

III. Main functions

3.1 Maps by level

folium displays maps in the class , which is declared as follows

class (location=None, width='100%', height='100%', left='0%', top='0%', position='relative', tiles='OpenStreetMap', attr=None, min_zoom=0, max_zoom=18, zoom_start=10, min_lat=-90, max_lat=90, min_lon=-180, max_lon=180, max_bounds=False, crs='EPSG3857', control_scale=False, prefer_canvas=False, no_touch=False, disable_3d=False, png_enabled=False, zoom_control=True, **kwargs)

Let's talk about a few important parameters

  • location latitude and longitude, in list or tuple format, in latitude, longitude order
  • zoom_start zoom value, default is 10, the larger the value, the smaller the scale, the larger the zoom level of the map.
  • tiles display style, default *'OpenStreetMap'*, that is, turn on the street display
  • crs Georeferencing system, default "EPSG3857".

3.1.1 World map

import folium

print(folium.__version__)

# define the world map
world_map = ()
# display world map
world_map

image-20200309205212588

3.1.2 Country maps

# define the national map
national_map = (location=[35.3, 100.6], zoom_start=4)
# display national map
national_map

image-20200310014116766

3.1.3 Municipal maps

In fact, to change the map display is to change the latitude and longitude of the display and zoom ratio, provincial, municipal, county level usage is the same, here is an example of a municipal example, such as Beijing:

# define the city map
city_map = (location=[39.93, 116.40], zoom_start=10)
# display city map
city_map

image-20200309205918570

The display is really not as good as Baidu's 😓.

3.2 Map forms

In addition to the normal map display described above, folium offers a very rich and varied display, which is controlled by the variabletilesThe styles areOpenStreetMap, Stamen Terrain, Stamen Toner, Mapbox Bright, Mapbox Control RoomAnd so on, here's a selection of some of the more common ones

# define the city map,tiles='Stamen Toner'
city_map = (location=[39.93, 116.40], zoom_start=10, tiles='Stamen Toner')
# display city map
city_map
# define the city map, tiles='Stamen Terrain'
city_map = (location=[39.93, 116.40], zoom_start=10, tiles='Stamen Terrain')
# display city map
city_map

Stamen Toner & Stamen Terrain

3.3 Marking on the map

3.3.1 General marking

Adding a common tag is done with theMarker

Here you can select the pattern of the marking.

bj_map = (location=[39.93, 115.40], zoom_start=12, tiles='Stamen Terrain')

(
    location=[39.95, 115.33],
    popup='Mt. Hood Meadows',
    icon=(icon='cloud')
).add_to(bj_map)

(
    location=[39.96, 115.32],
    popup='Timberline Lodge',
    icon=(color='green')
).add_to(bj_map)

(
    location=[39.93, 115.34],
    popup='Some Other Location',
    icon=(color='red', icon='info-sign')
).add_to(bj_map)

bj_map

image-20200309212826073

Adding a round mark is done with theCircle as well asCircleMarker

bj_map = (location=[39.93, 116.40], zoom_start=12, tiles='Stamen Toner')

(
    radius=200,
    location=[39.92, 116.43],
    popup='The Waterfront',
    color='crimson',
    fill=False,
).add_to(bj_map)

(
    location=[39.93, 116.38],
    radius=50,
    popup='Laurelhurst Park',
    color='#3186cc',
    fill=True,
    fill_color='#3186cc'
).add_to(bj_map)

bj_map

image-20200309212843415

3.3.2 Click to get latitude and longitude

m = (location=[46.1991, -122.1889],tiles='Stamen Terrain',zoom_start=13)

m.add_child(())

m

You can get the latitude and longitude of the click out by clicking the mouse.

Kapture 2020-03-09 at 22.00.40

3.3.3 Dynamic placement of markers

m = (
    location=[46.8527, -121.7649],
    tiles='Stamen Terrain',
    zoom_start=13
)

(
    [46.8354, -121.7325],
    popup='Camp Muir'
).add_to(m)

m.add_child((popup='Waypoint'))

m

Kapture 2020-03-11 at 10.39.44

3.4 Thermal mapping

Since there is no actual latitude and longitude coordinate data, only a few locations can be simulated out here, in addition to a value for each location as a thermal value.

# generated data
import numpy as np
data = (
    (size=(100, 3)) *
    ([[0.1, 0.1, 0.1]]) +
    ([[40, 116.5, 1]])
).tolist()
data[:3]

data distribution

[[40.04666663299843, 116.59569796477264, 0.9667425547098781],
 [39.86836537517533, 116.28201445195315, 0.8708549157348728],
 [40.08123232852134, 116.56884585184197, 0.9104952244371285]]

Heat mapping

# HeatMap
from  import HeatMap
m = ([39.93, 116.38], tiles='stamentoner', zoom_start=6)
HeatMap(data).add_to(m)
# (('results', ''))
m

image-20200310231553948

3.5 Density mapping

folium can not only plot heat maps, but also density maps, clustering examples by latitude and longitude, and then displaying them in the map.

from  import MarkerCluster

m = ([39.93, 116.38], tiles='stamentoner', zoom_start=10)

# create a mark cluster object
marker_cluster = MarkerCluster().add_to(m)

# add data point to the mark cluster
for lat, lng, label in data:
    (
        location=[lat, lng],
        icon=None,
        popup=label,
    ).add_to(marker_cluster)

# add marker_cluster to map
m.add_child(marker_cluster)

image-20200310232519456

3.6 Customizing map areas

A very advantageous feature of folium is the drawing of customized regions, as long as there is a region's boundary data, it can be shown in a variety of forms in the map, here to folium's official map of the United States as an example, the source data is an.json file, which contains characteristics (including a list of boundary latitudes and longitudes, abbreviations, etc.) for each region (U.S. states), theSource Data PortalThe format of the data is as follows:

image-20200310233211972

3.6.1 Drawing the boundary only, without adding data

If you only require the boundary to be drawn, without displaying information about the boundary region, then this is relatively easy, with the following code

import json
import requests

# read us-states border 
with open("") as f:
    us_states = (f)

us_map = (location=[35.3, -97.6], zoom_start=4)
(
    us_states,
    style_function=lambda feature: {
        'fillColor': '#ffff00',
        'color': 'black',
        'weight': 2,
        'dashArray': '5, 5'
    }
).add_to(us_map)

#display map
us_map

image-20200310233644765

3.6.2 Drawing the boundary and adding data

When you need to fill in the data in each region, this is slightly more troublesome, not only do you need the boundary data of each region, you also need the display information of each region, here also use the official U.S. state boundary data as an example:

import geopandas as gpd
import pandas as pd
import folium, branca

states = .from_features(us_states, crs=.from_epsg(4326))
()

image-20200311001008073

We then join the revenue and other data to the above table

abbrs = pd.read_json(open(""))
statesmerge = (abbrs,how='left', left_on='name', right_on='name')
statesmerge['geometry']=(.05)
income = pd.read_csv("", dtype={"fips":str})
income['income-2015']=pd.to_numeric(income['income-2015'], errors='coerce')
(by="state")[['state','income-2015']].median().head()
statesmerge['medianincome']=((by="state")[['state','income-2015']].median(), how='left', left_on='alpha-2', right_on='state')['income-2015']
statesmerge['change']=((by="state")[['state','change']].median(), how='left', left_on='alpha-2', right_on='state')['change']
()

image-20200311003029494

The final map that came out is as follows:

00831rSTly1gcpr4az8hdg30re0ggqv8

In addition, there are many other very interesting features, which are not listed here, and those interested can refer to the official documentation.

IV. Competitor Comparison and Advantages and Disadvantages

Domestic competitors are Baidu's pyecharts, and thefolium The same can be realized as a common map drawing function, but the specific use of the larger differences, specifically the following table

functionality pyecharts folium note
world map can can
Chinese display can Partially possible foliumRulers and text in the map cannot be displayed normally, but Chinese embedded in the map can be displayed normally.
interactivity (of an unmarried couple) be close (of an unmarried couple) be close
District (county) level maps can can foliumNeed for district (county) boundary data
Municipal Maps can can foliumMunicipal boundary data required
charging Customized area need to buy Baidu ak Customizable area features are free of charge
dexterity (of an unmarried couple) be close (of an unmarried couple) be close
Provincial Maps can can foliumNeed for provincial boundary data
aesthetics (of an unmarried couple) be close rather or relatively good
Customized area Partially possible can pyecharts need baidu ak.foliumfree (of charge)

V. References

[1] /question/33783546

[2] /project/folium/

[3] /github/python-visualization/folium/tree/master/examples/

To this article on the Python mapping artifact folium is introduced to this article, more related Python mapping folium content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!