我正在制作一张显示美国各州最低工资的地图。
我的代码生成的地图看起来不错,但图例是无序的,这很尴尬。我希望它按升序排列(即 $7.25-8、$8-9,...)。除此之外,图例标题目前仅表示“颜色”,我希望能够将其更改为更具描述性。我该怎么做?
这是我当前的代码:
import plotly.express as px
fig = px.choropleth(locations=df['state'],
locationmode='USA-states',
color=df['wage_cat'],
color_discrete_map={ '$7.25-8':'#e0e6f6',
'$8-9':'#c1ccee',
'$9-10':'#a2b3e5',
'$10-11':'#8399dd',
'$11-12':'#6480d4',
'$12-13':'#4566cb',
'$13-14':'#3353b7',
'$14-15':'#2a4598',
'$15-16':'#223779',
'$17-18':'#19295A',
'No state minimum wage':'#f9fafd'}
)
fig.update_layout(
title_text='State Minimum Wage as of 1-1-24',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True, # lakes
lakecolor='rgb(255, 255, 255)'),
)
fig.show()
您可以将
wage_cat
列设置为 CategoricalDtype
(请参阅文档此处),然后按 df
对 wage_cat
进行排序,然后再将其传递给 px.choropleth
。要更新图例标题,您可以使用 legend_title_text argument
中的 fig.update_layout
。
类似以下内容:
all_wage_categories = ['$7.25-8',
'$8-9',
'$9-10',
'$10-11',
'$11-12',
'$12-13',
'$13-14',
'$14-15',
'$15-16',
'$17-18',
'No state minimum wage']
df['wage_cat'] = pd.Categorical(df['wage_cat'],
categories=all_wage_categories,
ordered=True)
df = df.sort_values(by=['wage_cat'])
使用一些示例数据,这是一个完全可重现的示例:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
states = [ 'AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME',
'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM',
'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX',
'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY']
np.random.seed(42)
all_wage_categories = ['$7.25-8',
'$8-9',
'$9-10',
'$10-11',
'$11-12',
'$12-13',
'$13-14',
'$14-15',
'$15-16',
'$17-18',
'No state minimum wage']
wages = np.random.choice(all_wage_categories, size=51)
df = pd.DataFrame({
'state': states,
'wage_cat': wages
})
df['wage_cat'] = pd.Categorical(df['wage_cat'],
categories=all_wage_categories,
ordered=True)
df = df.sort_values(by=['wage_cat'])
fig = px.choropleth(locations=df['state'],
locationmode='USA-states',
color=df['wage_cat'],
color_discrete_map={ '$7.25-8':'#e0e6f6',
'$8-9':'#c1ccee',
'$9-10':'#a2b3e5',
'$10-11':'#8399dd',
'$11-12':'#6480d4',
'$12-13':'#4566cb',
'$13-14':'#3353b7',
'$14-15':'#2a4598',
'$15-16':'#223779',
'$17-18':'#19295A',
'No state minimum wage':'#f9fafd'}
)
fig.update_layout(
title_text='State Minimum Wage as of 1-1-24',
legend_title_text='Wage Category',
geo = dict(
scope='usa',
projection=go.layout.geo.Projection(type = 'albers usa'),
showlakes=True, # lakes
lakecolor='rgb(255, 255, 255)'),
)
fig.show()