如何在Python中创建choropleth映射?

2024-10-04 11:35:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用下面的pandas数据框创建choropleth地图

df.head()
Postal  Code   Latitude   Longitude  Average Price
0        M1B  43.806686  -79.194353  $880,124
1        M1C  43.784535  -79.160497  $1,416,183
2        M1E  43.763573  -79.188711  $1,081,779
3        M1G  43.770992  -79.216917  $912,943
4        M1H  43.773136  -79.239476  $929,923

使用此数据创建地图的最佳方法是什么


Tags: 数据pandasdf地图codepriceheadaverage
1条回答
网友
1楼 · 发布于 2024-10-04 11:35:54

python中有几个可用的地图可视化库。作为一个例子,我将展示plotly和mapbox的组合。这需要获取mapbox的APIkey

import pandas as pd
import numpy as np
import io

data = '''
"Postal  Code"   Latitude   Longitude  "Average Price"
0        M1B  43.806686  -79.194353  $880,124
1        M1C  43.784535  -79.160497  $1,416,183
2        M1E  43.763573  -79.188711  $1,081,779
3        M1G  43.770992  -79.216917  $912,943
4        M1H  43.773136  -79.239476  $929,923
'''

df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
df['Average Price'] = df['Average Price'].str.replace(',','').str.replace('$','').astype(int)

import plotly.express as px
px.set_mapbox_access_token(open("mapbox_API_key.txt").read())

fig = px.scatter_mapbox(df, lat="Latitude", lon="Longitude", color="Average Price", size="Average Price",
                  color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10)
fig.show()

enter image description here

相关问题 更多 >