Using Folium for Map Creation in Python
Folium is a Python library that creates interactive Leaflet maps directly from Python data structures. It bridges the gap between data analysis in Pandas and geographic visualization, allowing you to create professional-quality maps with minimal code. Folium supports tile layers from OpenStreetMap, Mapbox, CartoDB, and other providers, along with markers, choropleths, heatmaps, and popups for data exploration.
Basic Map Creation
Creating a map with Folium starts with the folium.Map constructor, which takes a location (latitude, longitude), zoom level, and tile style as parameters. The default tile set is OpenStreetMap, but you can switch to Stamen Terrain, CartoDB Positron, or other styles to match your aesthetic needs. Maps are HTML widgets that can be displayed in Jupyter notebooks, saved as standalone HTML files, or embedded in web pages.
import folium
# Create a base map centered on New York City
m = folium.Map(location=[40.7128, -74.0060], zoom_start=12,
tiles="CartoDB positron")
m.save("nyc_map.html")
# Create a map with different tile styles
m_terrain = folium.Map(location=[40.7128, -74.0060],
tiles="Stamen Terrain", zoom_start=11)
m_terrain.save("nyc_terrain.html")
Markers and Popups
Markers pinpoint locations on the map. Folium’s Marker class takes a location (lat, lng) and optional popup text or tooltip. For large datasets, using CircleMarker instead of the default icon marker improves performance—they render as SVG circles that scale well with hundreds of points. You can customize marker colors, icons (using Font Awesome or Bootstrap icons), and popup content to include formatted text, images, or even charts rendered as HTML.
import folium, pandas as pd
m = folium.Map(location=[40.7128, -74.0060], zoom_start=11)
# Sample data: coffee shops
shops = [
{"name": "Blue Bottle", "lat": 40.7266, "lng": -73.9968, "rating": 4.5},
{"name": "Stumptown", "lat": 40.7295, "lng": -73.9965, "rating": 4.3},
{"name": "Intelligentsia", "lat": 40.7282, "lng": -73.9943, "rating": 4.4},
]
for shop in shops:
color = "green" if shop["rating"] >= 4.4 else "orange"
folium.CircleMarker(
location=[shop["lat"], shop["lng"]],
radius=12, color=color, fill=True, fill_opacity=0.7,
popup=f"{shop['name']}
Rating: {shop['rating']}/5",
tooltip=shop["name"]
).add_to(m)
m.save("coffee_shops.html")
Choropleth Maps for Geographic Data
Choropleth maps color geographic regions (countries, states, districts) based on a data value. Folium’s choropleth layer requires two inputs: a GeoJSON file defining region boundaries, and a data column mapping each region ID to a value. This is powerful for visualizing election results, population density, infection rates, or economic indicators by region. The key is matching the GeoJSON feature IDs to your data keys—usually ISO country codes or FIPS state codes.
import folium, json, pandas as pd
m = folium.Map(location=[39.8, -98.5], zoom_start=4)
# Unemployment data by state (simulated)
data = pd.DataFrame({
"state": ["AL", "AK", "AZ", ...], # state FIPS or abbreviation
"unemployment": [4.2, 5.1, 3.8, ...]
})
folium.Choropleth(
geo_data="us-states.json", # GeoJSON file
name="choropleth",
data=data,
columns=["state", "unemployment"],
key_on="feature.id",
fill_color="YlOrRd",
fill_opacity=0.7,
line_opacity=0.2,
legend_name="Unemployment Rate (%)"
).add_to(m)
m.save("unemployment.html")
Heatmaps and Clustering
For visualizing point density (e.g., crime locations, taxi pickups, earthquake epicenters), Folium offers HeatMap (from folium.plugins) which renders a smooth density surface where color intensity represents point concentration. The MarkerCluster plugin groups nearby markers into clusters that expand as you zoom in, making it practical to display thousands of points without overwhelming the browser. Both plugins integrate seamlessly with Folium’s API and work well in Jupyter notebooks and web dashboards. Folium maps can also be combined with other visualization libraries—for example, using Altair to generate a chart and embedding it in a map popup, giving you the full power of the Python data visualization ecosystem on an interactive geographic canvas.
GeoPandas Integration
GeoPandas extends Pandas with geospatial data types (GeoSeries, GeoDataFrame) and operations (buffer, intersection, distance, convex hull). Folium maps can directly visualize GeoDataFrames using the explore() method, which accepts a GeoDataFrame and automatically creates a choropleth or point map. This integration enables complex spatial analysis pipelines: load shapefiles or GeoJSON with GeoPandas, perform spatial operations (filter points within a polygon, compute nearest neighbors), and visualize results with Folium in a few lines of code. The combination of GeoPandas for analysis and Folium for visualization covers 90% of geospatial data science workflows without requiring GIS desktop software.
import geopandas as gpd
# Load world countries shapefile
world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
# Filter to a continent
asia = world[world["continent"] == "Asia"]
# Create Folium map
m = asia.explore(column="pop_est", cmap="YlOrRd", legend=True)
m.save("asia_population.html")
Real-Time Data with Folium
Folium maps can display real-time data by updating markers dynamically. While Folium itself generates static HTML, combining it with JavaScript setInterval() calls to refresh GeoJSON data sources creates live-updating maps. For production dashboards, consider using Streamlit with st_folium which supports bidirectional communication between Python and the map. The folium.plugins package adds TimestampedGeoJson for animating data over time, Draw for user input, and Fullscreen for presentation mode. Folium’s FeatureGroup organizes related markers into toggleable layers. The integration with ipyleaflet provides higher performance for interactive exploration with WebGL support for millions of points.



