如何提取Plotly hexbin_mapbox中六边形的质心、顶点及均值到DataFrame
提取Plotly Hexbin热力图的六边形数据到Pandas DataFrame
要导出hexbin热力图中每个六边形的均值、质心坐标和顶点坐标,直接从Plotly生成的fig对象中提取数据即可,具体步骤如下:
数据提取逻辑
Plotly的create_hexbin_mapbox生成的图表对象中,六边形的核心数据存储在fig.data[0](第一个图层为hexbin图层,第二个是原始点图层):
- 每个六边形的均值:
fig.data[0].z数组 - 质心GPS坐标:
fig.data[0].lat(纬度)和fig.data[0].lon(经度)数组 - 六个顶点GPS坐标:
fig.data[0].geojson['features']中的每个feature包含geometry.coordinates,存储的是六边形的顶点经纬度(注意顺序为经度, 纬度)
完整实现代码
在你提供的示例代码末尾添加以下提取逻辑:
# 提取hexbin图层数据 hexbin_layer = fig.data[0] # 1. 准备基础数据:均值、质心坐标 hex_data = pd.DataFrame({ 'mean_value': hexbin_layer.z, 'centroid_lat': hexbin_layer.lat, 'centroid_lon': hexbin_layer.lon }) # 2. 提取每个六边形的顶点坐标 vertices_list = [] for feature in hexbin_layer.geojson['features']: # 获取顶点坐标(lon, lat),最后一个点和第一个点重复,取前6个 coords = feature['geometry']['coordinates'][0][:-1] # 转换为lat, lon并整理成字典 vertices = {f'vertex_{i+1}_lat': coord[1] for i, coord in enumerate(coords)} vertices.update({f'vertex_{i+1}_lon': coord[0] for i, coord in enumerate(coords)}) vertices_list.append(vertices) # 合并顶点数据到主DataFrame hex_data = pd.concat([hex_data, pd.DataFrame(vertices_list)], axis=1) # 查看结果 display(hex_data)
结果说明
最终生成的hex_data DataFrame包含以下字段:
mean_value:对应每个六边形的均值centroid_lat/centroid_lon:六边形质心的纬度和经度vertex_1_lat到vertex_6_lat:六个顶点的纬度vertex_1_lon到vertex_6_lon:六个顶点的经度
内容的提问来源于stack exchange,提问作者BGG16
相关产品推荐
相关产品推荐

