gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:08:00 25 4
gpt4 key购买 nike

我有这样的数据:

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

我正在绘制条形图: enter image description here

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

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
)

enter image description here

第二个 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"})

关于python - 在绘图中结合条形图和线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71590989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com