如何用Python制作交互式地理图并嵌入WordPress文章
使用Python创建交互式地理图并嵌入WordPress的完整流程
一、工具选型说明
你提到的matplotlib是静态绘图库,无法直接生成交互式HTML地图。结合geopandas处理地理数据的需求,推荐用Folium(专注地图可视化)或Plotly Express(通用交互式可视化)来生成符合需求的交互式地图,两者都能直接导出HTML文件,适配WordPress嵌入。
二、步骤详解
1. 环境与数据准备
先安装必要依赖:
pip install geopandas folium plotly pandas
用geopandas加载地理数据(比如巴黎行政区的GeoJSON/Shapefile),并关联业务数据(如租房价格):
import geopandas as gpd import pandas as pd # 加载地理边界数据(示例为巴黎行政区GeoJSON) paris_districts = gpd.read_file("paris_districts.geojson") # 关联租房价格数据(假设已准备好csv) rental_data = pd.read_csv("paris_rental_prices.csv") # 合并地理数据与业务数据 merged_data = paris_districts.merge(rental_data, on="district_id") # 转换为Folium/Plotly支持的坐标系(EPSG:4326) merged_data = merged_data.to_crs(epsg=4326)
2. 用Folium创建交互式地图
Folium基于Leaflet.js,生成的地图交互性强,适合地理场景:
import folium # 初始化地图,中心设为巴黎 m = folium.Map(location=[48.8566, 2.3522], zoom_start=12) # 添加 choropleth 图层(根据租金价格着色) folium.Choropleth( geo_data=merged_data, name="租金分布", data=merged_data, columns=["district_name", "avg_rent"], key_on="feature.properties.district_name", fill_color="YlOrRd", fill_opacity=0.7, line_opacity=0.2, legend_name="平均租金(欧元/㎡)" ).add_to(m) # 添加 tooltip,鼠标悬停显示详情 folium.GeoJsonTooltip( fields=["district_name", "avg_rent", "sample_count"], aliases=["行政区", "平均租金", "样本数"], localize=True ).add_to(folium.GeoJson(merged_data).add_to(m)) # 保存为HTML文件 m.save("paris_rental_map.html")
3. 用Plotly创建交互式地图
Plotly的交互样式更丰富,支持更多自定义:
import plotly.express as px fig = px.choropleth_mapbox( merged_data, geojson=merged_data.geometry, locations=merged_data.index, color="avg_rent", color_continuous_scale="YlOrRd", mapbox_style="carto-positron", zoom=11, center={"lat": 48.8566, "lon": 2.3522}, hover_data=["district_name", "sample_count"], title="2023巴黎公寓租金市场分布" ) fig.update_layout(margin={"r":0,"t":30,"l":0,"b":0}) # 保存为HTML文件 fig.write_html("paris_rental_plotly.html")
4. 嵌入WordPress文章
有两种可靠方式:
- 方法1:IFrame嵌入(推荐)
- 将导出的
paris_rental_map.html上传到你的WordPress服务器(比如/wp-content/uploads/maps/目录) - 在文章编辑页添加「自定义HTML」块,插入IFrame代码:
<iframe src="https://你的域名/wp-content/uploads/maps/paris_rental_map.html" width="100%" height="600px" frameborder="0" scrolling="no"></iframe>
- 将导出的
- 方法2:直接嵌入HTML代码
打开导出的HTML文件,复制<body>内的所有代码(包含JS和地图元素),粘贴到WordPress的「自定义HTML」块中。注意:部分WordPress主题或安全插件可能过滤JS代码,需确保编辑器处于「文本模式」而非「可视化模式」,或调整安全插件的过滤规则。
三、关于Matplotlib的补充
如果一定要用matplotlib生成静态图再转交互式,可使用mpld3库:
import matplotlib.pyplot as plt import mpld3 # 用matplotlib绘制静态地理图 fig, ax = plt.subplots(1, 1) merged_data.plot(column="avg_rent", ax=ax, legend=True) # 转换为交互式HTML html_str = mpld3.fig_to_html(fig) with open("matplotlib_interactive_map.html", "w") as f: f.write(html_str)
但这种方式的地图交互体验远不如Folium/Plotly,仅作为备选方案。
内容的提问来源于stack exchange,提问作者Daniel Kharlamov
相关产品推荐
相关产品推荐

