提问人:PBI1910 提问时间:10/5/2023 最后编辑:Derek OPBI1910 更新时间:10/5/2023 访问量:45
Geopandas Choropleth 的标签
Label for Geopandas Choropleth
问:
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
df_sample = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv')
df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply(lambda x: str(x).zfill(2))
df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply(lambda x: str(x).zfill(3))
df_sample['FIPS'] = df_sample['State FIPS Code'] + df_sample['County FIPS Code']
colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1",
"#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9",
"#08519c", "#0b4083", "#08306b"
]
endpts = list(np.linspace(1, 12, len(colorscale) - 1))
fips = df_sample['FIPS'].tolist()
values = df_sample['Unemployment Rate (%)'].tolist()
fig = ff.create_choropleth(
fips=fips, values=values, scope=['usa'],
binning_endpoints=endpts, colorscale=colorscale,
show_state_data=False,
show_hover=True,
asp = 2.9,
title_text = 'USA by Unemployment %',
legend_title = '% unemployed'
)
fig.layout.template = None
fig.show()
知道如何为此代码添加标签吗?将鼠标悬停在地图上时,我需要 fips 详细信息。
由于代码使用了列表,因此不确定如何包含标签和悬停。
答:
1赞
r-beginners
10/5/2023
#1
figure factory
是过去的库,目前不推荐使用。根据参考中的示例创建所需的地图。首先,您将需要 geojson,我们将为县填充引入它。就业人数和非就业人数将添加为基本地图的悬停数据。作为标签的示例,您可以使用 go 将县名称添加为注释。Scattergeo 的文本模式。该地图仅限于加利福尼亚州,以便更好地理解标注。
import plotly.graph_objects as go
import plotly.express as px
# State: 06 -> California
fig = px.choropleth(df_sample[df_sample.FIPS.str.startswith("06")],
geojson=counties,
locations='FIPS',
color='Unemployment Rate (%)',
hover_data=['Employed','Unemployed'],
scope='usa',
color_continuous_scale="Blues",
range_color=[0, 12.0],
color_continuous_midpoint=6.87,
basemap_visible=False,
title = 'USA by Unemployment %',
labels={'unemp': '% unemployed'},
)
# State: 06 -> California
fig.add_trace(go.Scattergeo(geojson=counties,
locations=df_sample[df_sample.FIPS.str.startswith("06")]['FIPS'],
text=df_sample[df_sample.FIPS.str.startswith("06")]['County Name/State Abbreviation'].apply(lambda x: x.split(' ')[0]),
textfont=dict(size=8, color='red'),
mode='text')
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_traces(marker_line_width=0)
fig.update_layout(template=None, height=500, margin={"r":0,"t":0,"l":0,"b":0}, coloraxis_showscale=False)
fig.show()
评论