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()
Any idea how to add labels to this code? I need the fips details while hover over the map.
Since the code used the list, not sure how to include label and hover.
figure factory
is a past library and is not currently recommended. Create your desired map based on the examples in the reference. First, you will need geojson, which we will introduce for the county fill. The number of employed and non-employed people is added as hover data for the basic map. As an example of labels, you can add the county name as an annotation by using go.Scattergeo’s text mode. The map is limited to California only so that the labels can be better understood.
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()