python-3.x Geopandas Choropleth标签

ubof19bj  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(156)
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的细节,而悬停在Map上。
由于代码中使用了列表,不知道如何包含label和hover。

enxuqcxy

enxuqcxy1#

figure factory是过去的库,目前不推荐使用。根据参考中的示例创建所需的Map。首先,您需要geojson,我们将为县填充引入它。就业人数和非就业人数被添加为基本Map的悬停数据。作为标签的一个例子,您可以使用go.Scattergeo的文本模式将县名作为注解添加。Map仅限于加州,以便更好地理解标签。

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()

相关问题