Python provides a robust ecosystem for creating interactive geospatial visualizations, moving beyond the limitations of static plotting libraries. Two prominent libraries, Pyecharts and Folium, allow developers to build dynamic, web-ready maps with complex data overlays. This guide explores the implementation of these tools to generate choropleth maps, coordinate scatter plots, heatmaps, and clustered markers.
Pyecharts Implementation
Pyecharts is a versatile wrapper around Apache ECharts. It supports chainable method calls and distinct configuration objects, making it ideal for building complex visualizations. The library requires specific extensions to render different administrative boundaries.
Installation and Setup
Begin by installing the core library and the necessary map packages for global and regional data:
pip install pyecharts
pip install echarts-countries-pypkg
pip install echarts-china-provinces-pypkg
pip install echarts-china-cities-pypkg
pip install echarts-china-counties-pypkg
Creating Choropleth Maps
To visualize regional data, such as economic indicators, the Map class is utilized. The data must be formatted as a list of lists, where each sub-list contains a region name and its corresponding value.
import pandas as pd
from pyecharts.charts import Map
from pyecharts import options as opts
from pyecharts.globals import ThemeType
# Load regional data
df_stats = pd.read_excel('regional_stats.xlsx')
region_names = df_stats['province'].tolist()
data_values = df_stats['2023_metric'].tolist()
# Prepare data pairs: [[Region, Value], ...]
chart_data = [[reg, val] for reg, val in zip(region_names, data_values)]
# Initialize and configure the map
regional_map = (
Map(init_opts=opts.InitOpts(width="1000px", height="600px", theme=ThemeType.DARK))
.add(
series_name="Economic Output",
data_pair=chart_data,
maptype="china"
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Regional Economic Distribution (2023)"),
visualmap_opts=opts.VisualMapOpts(
min_=1000,
max_=120000,
is_piecewise=True,
split_number=8,
pos_left="left",
pos_top="center",
orient="vertical"
)
)
.render("regional_choropleth.html")
)
Geographic Scatter Plots with Geo
The Geo class is suitable for plotting coordinate-based data or named locations with custom symbols. It supports effects like ripples (dynamic scattering) to highlight specific data points.
from pyecharts.charts import Geo
from pyecharts.globals import ChartType
geo_chart = (
Geo()
.add_schema(maptype="china")
.add(
"Key Locations",
chart_data,
symbol_size=15,
type_=ChartType.EFFECT_SCATTER,
color="#FF0000"
)
.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
.set_global_opts(
title_opts=opts.TitleOpts(title="Geographic Distribution Analysis"),
visualmap_opts=opts.VisualMapOpts(max_=120000)
)
.render("geo_effect_scatter.html")
)
Baidu Maps Integration (BMap)
For street-level detail and specific basemaps, Pyecharts integrates with Baidu Maps via the BMap class. This requires a valid Baidu Maps API Key (AK).
from pyecharts.charts import BMap
bmap_chart = (
BMap(init_opts=opts.InitOpts(width="1000px", height="600px"))
.add_schema(
baidu_ak="YOUR_BAIDU_AK",
center=[116.404, 39.915],
zoom=5
)
.add(
"Heatmap",
chart_data, # Requires coordinates [lng, lat] for precise mapping
type_=ChartType.HEATMAP,
label_opts=opts.LabelOpts(formatter="{b}")
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Baidu Heatmap Overlay"),
visualmap_opts=opts.VisualMapOpts(pos_right="bottom", pos_top="center")
)
.render("baidu_heatmap.html")
)
Folium Implementation
Folium leverages the leaflet.js library to create lightweight, interactive maps. It excels at handling large datasets of latitude and longitude coordinates and supports various tile layers.
Heatmap Visualization
Using a dataset of Points of Interest (POI), such as city attractions, a heatmap can visualize density. The example below uses the Stamen Terrain tileset for better topographical context.
import pandas as pd
import folium
from folium.plugins import HeatMap
# Load coordinates
df_poi = pd.read_csv('city_attractions.csv')
# Define map center and tileset
heat_map = folium.Map(
location=[23.1291, 113.2644],
zoom_start=12,
tiles="Stamen Terrain",
control_scale=True
)
# Extract coordinate pairs
heat_data = [[row['lat'], row['lon']] for idx, row in df_poi.iterrows()]
# Add heatmap layer
HeatMap(heat_data, radius=12, blur=15).add_to(heat_map)
# Add central marker
folium.Marker(
[23.1291, 113.2644],
popup="City Center",
icon=folium.Icon(color='green', icon='cloud')
).add_to(heat_map)
heat_map.save("folium_heatmap.html")
Marker Clustering
When visualizing thousands of points, individual markers can clutter the map. The MarkerCluster plugin groups nearby points into clusters that expand upon interaction.
from folium.plugins import MarkerCluster
cluster_map = folium.Map(
location=[23.1291, 113.2644],
zoom_start=12,
tiles="Stamen Toner"
)
# Initialize cluster
marker_cluster = MarkerCluster(name="Attraction Clusters").add_to(cluster_map)
# Iterate and add markers
for idx, row in df_poi.iterrows():
folium.Marker(
location=[row['lat'], row['lon']],
popup=row['name'],
icon=folium.Icon(color='blue', icon='info-sign')
).add_to(marker_cluster)
folium.LayerControl().add_to(cluster_map)
cluster_map.save("folium_cluster_map.html")