首页 > 解决方案 > 绘图添加跟踪比较

问题描述

如何在散点图上添加一条比较线,并带有一条保持我的 x 轴的轨迹。在第一行中,它表示 x 轴上显示的范围,但第二行是前 30 天,但即使没有范围也会显示

datastudio 图比较

这是我的图表和我的代码,它目前有另一行但在不同的范围内,这就是它不显示的原因

绘图

 fig = px.scatter(df_grouped, x=x, y=y, template=layout, height=200, width=530, color_discrete_sequence=palette)
 fig.add_trace(go.Scatter(x=df_grouped[x], y=df_grouped[y], mode='lines'))
 fig.add_trace(go.Scatter(x=df_grouped[x], y=df_grouped_last[y], mode='lines'))

标签: pythonplotlyplotly-dash

解决方案


  • 您可以准备数据框以将上个月与当前月对齐
  • 然后你可以生成数字。没有专注于美化,只是接近
df = pd.DataFrame(
    {
        "date": pd.date_range("5-sep-2021", freq="W", periods=8),
        "line1": np.random.uniform(20, 30, 8),
        "line2": np.random.uniform(20, 30, 8),
    }
)

# prep dataframe to bring previous month aligned with current month
dfp = pd.merge(df, df, left_on="date", right_on=df["date"] + pd.Timedelta("28D"), suffixes=(" current", " previous"))

# plot current month and add previous month with additional hover info
px.line(dfp, x="date", y=["line1 current", "line2 current"]).add_traces(
    px.line(dfp, x="date", y=["line1 previous", "line2 previous"], hover_data=["date previous"]).data
)

在此处输入图像描述


推荐阅读