在绘图中结合条形图和线图

Sht*_*Sht 2 python 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)
    }
)
Run Code Online (Sandbox Code Playgroud)

我正在绘制条形图: 在此输入图像描述

我想添加“真实”变量的绘图线图。我正在使用以下命令:

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']))
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*ond 5

  • 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
)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

第二个 y 轴

根据评论更新

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"})
Run Code Online (Sandbox Code Playgroud)