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

如何用plotly.graph_objects.Scatter实现与px.scatter相同的边际图效果?

用Plotly Graph Objects实现散点图+边际直方图效果

要在Plotly Graph Objects中实现和px.scatter的marginal_x/marginal_y相同的边际图效果,需要通过**子图布局(subplots)**手动组合散点图与直方图,步骤如下:

核心思路

  1. 创建2行2列的子图布局,分配主散点图、顶部x轴边际直方图、右侧y轴边际直方图的位置
  2. 启用轴共享,保证主图与边际图的轴交互联动
  3. 分别添加散点图和直方图到对应子图位置
  4. 调整布局细节,隐藏冗余的轴标签/刻度,让整体效果更紧凑

完整代码示例

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px

# 示例数据集(可替换为你的df)
df = px.data.iris()

# 创建子图布局:顶部为x直方图,右侧为y直方图,中间为主散点图
fig = make_subplots(
    rows=2, cols=2,
    specs=[[{"type": "histogram"}, None],
           [{"type": "scatter"}, {"type": "histogram"}]],
    shared_xaxes=True,
    shared_yaxes=True,
    vertical_spacing=0.03,  # 减小垂直间距
    horizontal_spacing=0.03 # 减小水平间距
)

# 添加主散点图
fig.add_trace(
    go.Scatter(
        x=df['sepal_length'],
        y=df['sepal_width'],
        mode='markers',
        marker=dict(color='steelblue', opacity=0.7)
    ),
    row=2, col=1
)

# 添加顶部x轴边际直方图
fig.add_trace(
    go.Histogram(
        x=df['sepal_length'],
        nbinsx=20,
        marker=dict(color='steelblue', opacity=0.5)
    ),
    row=1, col=1
)

# 添加右侧y轴边际直方图(横向布局对齐主图y轴)
fig.add_trace(
    go.Histogram(
        y=df['sepal_width'],
        nbinsy=20,
        marker=dict(color='steelblue', opacity=0.5),
        orientation='h'
    ),
    row=2, col=2
)

# 优化边际图的轴显示:隐藏刻度和无意义的标题
fig.update_xaxes(showticklabels=False, title_text='', row=1, col=1)
fig.update_yaxes(showticklabels=False, title_text='', row=2, col=2)

# 设置主图的轴标题
fig.update_xaxes(title_text='Sepal Length', row=2, col=1)
fig.update_yaxes(title_text='Sepal Width', row=2, col=1)

# 调整整体布局
fig.update_layout(
    title='Scatter Plot with Marginal Histograms',
    height=600,
    width=800,
    showlegend=False
)

fig.show()

关键细节说明

  • specs参数:指定每个子图的类型,None表示该位置留空,避免布局混乱
  • shared_xaxes/shared_yaxes:开启后,拖动主图轴时边际图会同步联动,和px的交互体验一致
  • orientation='h':让右侧的y直方图横向显示,完美匹配px中marginal_y的视觉效果
  • 调整vertical_spacing/horizontal_spacing:缩小子图间距,让整体布局更紧凑,接近px的默认样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:30:44