简体   繁体   中英

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

Hi I'm currently working with a dataset of new Covid-19 cases per 100k people for every county in the US.

Dataset:

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
...

I was able to have a Choropleth map that captures any single week. In this case, week 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()

How do I create a slider that can display snapshots of each week. I assume that I need to map the slider to the value of the color attribute, but not sure how to go about this.

Thanks.

The data format needs to be converted to a vertical format instead of a horizontal format. The next step is to add an animation frame in the map settings. Specify the name of the week that will become the slider. Since the data is partial, I narrowed down the range to see if it was working correctly.

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM