如何用Python的Plotly修改代码实现超市销售数据气泡地图?
缅甸城市销售数据气泡地图实现方案
核心修改思路
原示例是基于国家代码的全球地图,要适配城市级别的缅甸数据,需要做以下关键调整:
- 替换数据源为你的超市销售数据集
- 补充城市经纬度信息(原数据集未包含)
- 按城市聚合计算总销售数量,作为气泡大小的依据
- 使用经纬度定位城市,而非国家代码
完整实现代码
import plotly.express as px import pandas as pd # 读取超市销售数据集(使用原始文件链接) df = pd.read_csv("https://raw.githubusercontent.com/selva86/datasets/master/supermarket_sales.csv") # 按城市分组,计算每个城市的总销售数量 city_total_sales = df.groupby("City")["Quantity"].sum().reset_index() # 添加缅甸三个城市的经纬度坐标 city_location = { "Yangon": (16.8000, 96.1667), "Naypyitaw": (19.7500, 96.0833), "Mandalay": (21.9588, 96.0891) } city_total_sales["latitude"] = city_total_sales["City"].map(lambda x: city_location[x][0]) city_total_sales["longitude"] = city_total_sales["City"].map(lambda x: city_location[x][1]) # 创建气泡地图 fig = px.scatter_geo( city_total_sales, lat="latitude", lon="longitude", hover_name="City", size="Quantity", # 气泡大小对应总销售数量 color="City", # 不同城市用不同颜色区分 projection="natural earth", title="缅甸城市超市销售数量分布" ) # 调整地图视角,聚焦缅甸区域 fig.update_geos( center=dict(lat=20, lon=96), zoom=5 ) fig.show()
代码说明
- 数据读取:使用原始文件链接直接读取GitHub上的数据集,避免网页格式干扰
- 数据聚合:通过
groupby计算每个城市的总销量,确保气泡大小能反映整体销售规模 - 地理坐标补充:手动添加三个城市的经纬度,这是绘制城市级地图的必要前提
- 地图配置:通过
update_geos调整地图中心和缩放级别,让缅甸区域在视图中更清晰突出
内容的提问来源于stack exchange,提问作者janinedk
相关产品推荐
相关产品推荐

