- 考虑了两种不同的方法
- 首先将
dfs 构造成与您描述的相似
import requests
import io
import pandas as pd
import plotly.express as px
# fmt: off
# case / death data
dfall = pd.read_csv(io.StringIO(
requests.get("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
dfall["date"] = pd.to_datetime(dfall["date"])
countries = ['Australia', 'Austria', 'France', 'Germany', 'Japan', 'New Zealand', 'Singapore', 'United Kingdom', 'United States']
# fmt: on
# mimic described dict of dataframes
dfs = {c: dfall.loc[dfall["location"].eq(c), ["date", "new_cases"]] for c in countries}
方法一 - 将所有数据帧绘制为轨迹
- 构造
dfs中所有数据帧的拼接数据帧
-
updatemenus 是标准跟踪可见性用例
px.line(
pd.concat([dfs[c].assign(country=c) for c in dfs.keys()]),
x="date",
y="new_cases",
color="country",
).update_traces(visible=False).update_layout(
updatemenus=[
{
"buttons": [
{
"label": c,
"method": "update",
"args": [{"visible": [c == c2 for c2 in dfs.keys()]}],
}
for c in dfs.keys()
]
}
]
)
方法 2 - 更新菜单中的数据
- 在构造图形时,它必须有一个跟踪,因此使用
dfs 中的第一个数据帧
px.line(dfs[list(dfs.keys())[0]], x="date", y="new_cases").update_layout(
updatemenus=[
{
"buttons": [
{
"label": c,
"method": "restyle",
"args": [
{"x": [dfs[c]["date"]], "y": [dfs[c]["new_cases"]]},
],
}
for c in dfs.keys()
]
}
]
)
情节表达与子情节
- 有效地接近一个,每个国家/地区有多个踪迹
- 如果 country 在 hovertemplate 中,则建立真值列表
# mimic describe dict of dataframes
dfs = {
c: dfall.loc[
dfall["location"].eq(c), ["date", "new_cases", "new_deaths", "new_vaccinations"]
]
.set_index("date")
.stack()
.reset_index()
.rename(columns={"level_1": "measure", 0: "value"})
for c in countries
}
fig = (
px.line(
pd.concat([dfs[c].assign(country=c) for c in dfs.keys()]),
x="date",
y="value",
facet_row="measure",
color="country",
)
.update_layout({f"yaxis{n}": {"matches": None} for n in range(2, 6)})
.update_traces(visible=False)
)
fig.update_layout(
showlegend=False,
updatemenus=[
{
"buttons": [
{
"label": c,
"method": "update",
"args": [{"visible": [c in t.hovertemplate for t in fig.data]}],
}
for c in dfs.keys()
]
}
],
annotations=[
{**a, **{"text": a["text"].replace("measure=", "")}}
for a in fig.to_dict()["layout"]["annotations"]
],
)