目前正在使用美国城市数据集,以便在Jupyter Notebook项目中进行进一步分析。还是Python DS的业余爱好者,想制作一个交互式气泡图,显示每个美国城市的人口。提供照片中代码的输出。DataFrame的结构:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 19500 entries, 0 to 19499
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 US Pop Rank 19500 non-null int64
1 City 19500 non-null object
2 State 19500 non-null object
3 2019 Population 19500 non-null int64
4 Pop Growth 2000-2019 19383 non-null object
5 Longitude 19500 non-null float64
6 Latitude 19500 non-null float64
dtypes: float64(2), int64(2), object(3)
memory usage: 1.2+ MB
以及以下绘图代码:
Geographics['text'] = Geographics['City'] + '<br>Population ' + (Geographics['2019 Population']/1e6).astype(str)+' million'
limits = [(0,2),(3,10),(11,20),(21,50),(50,3000)]
colors = ["royalblue","crimson","lightseagreen","orange","lightgrey"]
cities = []
scale = 5000
fig = go.Figure()
for i in range(len(limits)):
lim = limits[i]
Geographics_sub = Geographics[lim[0]:lim[1]]
fig.add_trace(go.Scattergeo(
locationmode = 'USA-states',
lon = Geographics_sub['Longitude'],
lat = Geographics_sub['Latitude'],
text = Geographics_sub['text'],
marker = dict(
size = Geographics_sub['2019 Population']/scale,
color = colors[i],
line_color = 'rgb(40,40,40)',
line_width = 0.5,
sizemode = 'area'
),
name = '{0} - {1}'.format(lim[0],lim[1])))
fig.update_layout(
title_text = '2019 US city populations<br>(Click legend to toggle traces)',
showlegend = True,
geo = dict(
scope = 'usa',
landcolor = 'rgb(219, 219, 219)',
)
)
fig.show()
地图输出
顺序可能很重要,请尝试交换这些代码段,因为您可能会将映射放在散点之上。
Geographics['text'] = Geographics['City'] + '<br>Population ' + (Geographics['2019 Population']/1e6).astype(str)+' million'
limits = [(0,2),(3,10),(11,20),(21,50),(50,3000)]
colors = ["royalblue","crimson","lightseagreen","orange","lightgrey"]
cities = []
scale = 5000
fig = go.Figure()
fig.update_layout(
title_text = '2019 US city populations<br>(Click legend to toggle traces)',
showlegend = True,
geo = dict(
scope = 'usa',
landcolor = 'rgb(219, 219, 219)',
)
)
for i in range(len(limits)):
lim = limits[i]
Geographics_sub = Geographics[lim[0]:lim[1]]
fig.add_trace(go.Scattergeo(
locationmode = 'USA-states',
lon = Geographics_sub['Longitude'],
lat = Geographics_sub['Latitude'],
text = Geographics_sub['text'],
marker = dict(
size = Geographics_sub['2019 Population']/scale,
color = colors[i],
line_color = 'rgb(40,40,40)',
line_width = 0.5,
sizemode = 'area'
),
name = '{0} - {1}'.format(lim[0],lim[1])))
fig.show()