在 plotly 中结合条形图和线图

Combine Bar and line plot in plotly

我有这样的数据:

qq=df = pd.DataFrame(
    {
        "Predicted": np.sort(np.random.uniform(3, 15, 4)),
        "real": np.sort(np.random.uniform(3, 15, 4)),
        "Category":['A','B','C','D'],
        "new_val":np.random.uniform(3,15,4)
    }
)

我正在绘制条形图:

我想添加 'real' 变量的曲线图。 我正在使用以下命令:

px.bar(qq, x=qq['Category'], y=['Predicted', 'real', 'new_val'], title="Long-Form Input").add_trace(px.line(x=qq['Category'], y=qq['real']))

但这给了我错误: 我哪里错了?

  • 你想添加来自 px.line() 的轨迹而不是图形。因此 .data
  • 还更新了 px.line() 的痕迹,因此它会显示在图例中
import pandas as pd
import plotly.express as px

qq = pd.DataFrame(
    {
        "Predicted": np.sort(np.random.uniform(3, 15, 4)),
        "real": np.sort(np.random.uniform(3, 15, 4)),
        "Category": ["A", "B", "C", "D"],
        "new_val": np.random.uniform(3, 15, 4),
    }
)

px.bar(
    qq, x="Category", y=["Predicted", "real", "new_val"], title="Long-Form Input"
).add_traces(
    px.line(qq, x="Category", y="real").update_traces(showlegend=True, name="real").data
)

第二个轴

根据评论更新

import pandas as pd
import plotly.express as px

qq = pd.DataFrame(
    {
        "Predicted": np.sort(np.random.uniform(3, 15, 4)),
        "real": np.sort(np.random.uniform(3, 15, 4)),
        "Category": ["A", "B", "C", "D"],
        "new_val": np.random.uniform(3, 15, 4),
    }
)

px.bar(
    qq, x="Category", y=["Predicted", "real", "new_val"], title="Long-Form Input"
).add_traces(
    px.line(qq, x="Category", y="real").update_traces(showlegend=True, name="real", yaxis="y2").data
).update_layout(yaxis2={"side":"right", "overlaying":"y"})