如何为 Plotly Express 地图添加滑块?

How do I add a slider for a Plotly Express map?

您好,我目前正在处理美国每个县每 10 万人新 Covid-19 病例的数据集。

数据集:

County FIPS Week 1 Week 2 Week 3 Week 4 ...
01001 11.7390 11.7390 13.5299 11.7390
01003 4.5835 9.5110 17.5743 20.2621
01005 0.0000 9.1016 33.4078 33.4078
...

我能够得到一张可以捕捉任何一周的等值线图。在这种情况下,第 4 周。

from urllib.request import urlopen
import json

with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)
import plotly.express as px

fig = px.choropleth(df, 
                    geojson=counties,
                    locations='County FIPS',
                    color='Week 4',
                    color_continuous_scale="Viridis",
                    range_color=(0, 1000),
                    scope="usa",
                    labels={'cases': 'weekly cases'}
                    )
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()

如何创建一个可以显示每周快照的滑块。我假设我需要将滑块映射到颜色属性的值,但不确定如何去做。

谢谢。

需要将数据格式转换为垂直格式,而不是水平格式。下一步是在地图设置中添加动画帧。指定将成为滑块的星期名称。由于数据是部分数据,我缩小了范围以查看它是否正常工作。

from urllib.request import urlopen
import json
import pandas as pd
import numpy as np
import io

data = '''
"County FIPS" "Week 1" "Week 2" "Week 3" "Week 4"
01001 10.7394 10.7394 12.5293 10.7394 
01003 3.5837 8.5112 16.5745 19.2623 
01005 0.0000 8.1018 32.4070 32.4070
'''

df = pd.read_csv(io.StringIO(data), delim_whitespace=True, dtype={'County FIPS':'object'})

df = df.melt(id_vars='County FIPS', value_vars=df.columns, var_name='weeks')

with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)
import plotly.express as px

fig = px.choropleth(df, 
                    geojson=counties,
                    locations='County FIPS',
                    color='value',
                    color_continuous_scale="Viridis",
                    animation_frame='weeks',
                    range_color=(0, 50),
                    scope="usa",
                    labels={'cases': 'weekly cases'}
                    )
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()