【发布时间】:2021-10-12 23:53:42
【问题描述】:
【问题讨论】:
标签: python pandas jupyter-notebook plotly
【问题讨论】:
标签: python pandas jupyter-notebook plotly
import numpy as np
import pandas as pd
import plotly.express as px
# simulate data
df = pd.DataFrame({"Date": pd.date_range("1-jun-2020", "now")}).pipe(
lambda d: d.assign(**{"Time Per Ball (Seconds)": np.random.uniform(20, 51, len(d))})
)
fig = px.bar(df, x="Date", y="Time Per Ball (Seconds)")
dfbut = (
(df["Date"] + pd.offsets.MonthBegin(-1))
.drop_duplicates()
.to_frame()
.assign(
label=lambda d: d["Date"].dt.strftime("%b-%Y"),
start=lambda d: (d["Date"] - pd.Timestamp("1970-01-01")) // pd.Timedelta("1ms"),
end=lambda d: d["start"].shift(-1),
)
.fillna((df["Date"].max() - pd.Timestamp("1970-01-01")) // pd.Timedelta("1ms"))
)
# build buttons to filter by month
fig.update_layout(
updatemenus=[
{
"buttons": [
{
"label": r[1]["label"],
"method": "relayout",
"args": [{"xaxis": {"range": [r[1]["start"], r[1]["end"]]}}],
}
for r in dfbut.iterrows()
]
},
{"buttons":[{"label":"All data", "method":"relayout","args":[{"xaxis":{"range":[]}}]}],"y":.8,"type":"buttons"}
]
)
{"xaxis": {"autorange": True} 来维护视图切换之间的布局# add EndDate to make next part simpler
dfbut = dfbut.assign(EndDate=dfbut["Date"].shift(-1) - pd.Timedelta(days=1)).fillna(df["Date"].max())
dfbut = dfbut.loc[~(dfbut["EndDate"] < df["Date"].min())]
# create a trace per month so zoom / pan is maintained between selections
go.Figure(
[
px.bar(
df.loc[df["Date"].between(start, end)],
x="Date",
y="Time Per Ball (Seconds)",
)
.update_traces(name=label)
.data[0]
for label, start, end in dfbut.loc[:, ["label", "Date", "EndDate"]].values
]
).update_layout(
updatemenus=[
{
"buttons": [
{
"label": "All",
"method": "update",
"args": [
{"visible": (dfbut["label"] == dfbut["label"]).tolist()},
{"xaxis": {"autorange": True}},
],
}
]
+ [
{
"label": l,
"method": "update",
"args": [
{"visible": (dfbut["label"] == l).tolist()},
{"xaxis": {"autorange": True}},
],
}
for l in dfbut["label"]
]
}
],
xaxis={"autorange": True},
)
【讨论】: