You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Plotly Express叠加箱线图与散点图展示公司数据?

问题描述

我希望基于同一个Pandas DataFrame创建多层图表,其中一层为箱线图(boxplot),另一层为散点图(scatter plot),以此查看U9公司的位置。请问是否可以将这两个图表合并?

现有图表示例

箱线图

箱线图示例

散点图

散点图示例

当前代码

import pandas as pd 
import plotly.express as px

df = pd.read_csv("company_index.csv", sep=";", decimal=",")
print(df)

df_u9 = df.loc[df["company"].isin(["U9"])]

fig_1 = px.box(
        df,
        x="period",
        y="index"
    )
fig_2 = px.scatter(
        df_u9,
        x="period",
        y="index"
    )

fig_1.show()
fig_2.show()

数据文件(company_index.csv)

period;index;company
1;202,4;U1
1;226,69;U10
1;235,18;U9
1;236,49;U4
1;238,13;U2
1;244,05;U6
1;252,08;U3
1;256,68;U8
1;294,99;U5
1;299,391;U7
2;243,78;U1
2;264,26;U10
2;270,6;U2
2;272,89;U9
2;285,26;U5
2;289,29;U4
2;291,15;U6
2;291,19;U3
2;305,92;U7
2;314,65;U8
3;271,82;U1
3;278,65;U2
3;296,16;U10
3;297,21;U4
3;305,93;U6
3;308,96;U5
3;323,74;U9
3;335,93;U3
3;354,13;U8
3;381,2;U7
4;281,26;U5
4;308,5;U2
4;311,61;U1
4;334,03;U4
4;335,72;U9
4;344,32;U8
4;345,27;U6
4;355,44;U3
4;373,54;U7
4;381,68;U10
5;288,6;U1
5;305,66;U5
5;323,2;U2
5;358,46;U8
5;365,57;U3
5;366,96;U10
5;368,38;U7
5;371,23;U6
5;373,63;U4
5;422,93;U9
6;285,32;U5
6;291,65;U1
6;308,68;U2
6;372,04;U8
6;376,64;U3
6;403,55;U6
6;407,38;U4
6;420,65;U10
6;423,68;U9
6;453,09;U7
解决方案

完全可以合并这两个图表。在Plotly中,你可以通过fig.add_trace()方法将散点图的轨迹叠加到箱线图的图表对象上,实现图层融合。

修改后的代码如下:

import pandas as pd 
import plotly.express as px

# 读取数据
df = pd.read_csv("company_index.csv", sep=";", decimal=",")
df_u9 = df.loc[df["company"] == "U9"]

# 创建箱线图基础图表
fig = px.box(df, x="period", y="index")

# 将U9的散点轨迹添加到箱线图中
scatter_trace = px.scatter(df_u9, x="period", y="index", color_discrete_sequence=["red"]).data[0]
fig.add_trace(scatter_trace)

# 可选:自定义散点样式,让U9位置更突出
fig.update_traces(marker=dict(size=10, symbol="x"), selector=dict(mode="markers"))
fig.update_layout(title="各周期指数分布及U9公司位置", xaxis_title="周期", yaxis_title="指数")

fig.show()

代码说明

  • 先创建箱线图的基础图表对象fig
  • 通过px.scatter()生成散点图后,提取其第一个轨迹(data[0]),用add_trace()添加到箱线图中
  • 用color_discrete_sequence指定散点颜色,方便快速定位U9
  • update_traces和update_layout用于优化图表样式,提升可读性

内容的提问来源于stack exchange,提问作者404rorre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:30:45