Combine Bar and line plot in plotly

Viewed 251

I have this kind of data:

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)
    }
)

I am plotting Bar plot: enter image description here

I want to add this plot line plot of 'real' variable. I am using the following command:

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']))

But this gives me the error: Where am I wrong?

1 Answers
  • you want to add the traces from px.line() not the figure. Hence .data
  • have also updated the traces from px.line() so it will show in the legend
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
)

enter image description here

second yaxis

Update per comments

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"})
Related