1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #整理出注释和滑块步骤 annotation_text_template = "<b>Worldwide Totals</b>" \ "<br>{date}<br><br>" \ "Confirmed cases: {confirmed_cases:,d}<br>" \ "Deaths: {deaths:,d}<br>" \ "Mortality rate: {mortality_rate:.1%}" annotation_dict = { "x": 0.03, "y": 0.35, "width": 175, "height": 110, "showarrow": False, "text": "", "valign": "middle", "visible": False, "bordercolor": "black", }
steps = [] for i, data in enumerate(fig.data): step = { "method": "update", "args": [ {"visible": [False] * len(fig.data)}, {"annotations": [dict(annotation_dict) for _ in range(len(fig.data))]}, ], "label": dates_list[i], }
#将第i个跟踪和注释框切换到可见 step["args"][0]["visible"][i] = True step["args"][1]["annotations"][i]["visible"] = True
df = cases_by_date[dates_list[i]] confirmed_cases = df["confirmed_cases"].sum() deaths = df["deaths"].sum() mortality_rate = deaths / confirmed_cases step["args"][1]["annotations"][i]["text"] = annotation_text_template.format( date=dates_list[i], confirmed_cases=confirmed_cases, deaths=deaths, mortality_rate=mortality_rate, )
steps.append(step)
sliders = [ { "active": 0, "currentvalue": {"prefix": "Date: "}, "steps": steps, "len": 0.9, "x": 0.05, } ]
first_annotation_dict = {**annotation_dict} first_annotation_dict.update( { "visible": True, "text": annotation_text_template.format( date="10/01/2020", confirmed_cases=44, deaths=1, mortality_rate=0.0227 ), } ) fig.layout.title = {"text": "Covid-19 Global Case Tracker", "x": 0.5} fig.update_layout( height=650, margin={"t": 50, "b": 20, "l": 20, "r": 20}, annotations=[go.layout.Annotation(**first_annotation_dict)], sliders=sliders, ) fig.data[0].visible = True #设置第一个数据点可见
fig
|