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

Plotly Express:如何从边缘分布子图中移除趋势线?

简洁移除Plotly Express边缘分布子图中的趋势线

当使用Plotly Express的px.scatter同时设置marginal(边缘分布)和trendline(趋势线)参数时,边缘子图(顶部/右侧面板)会自动生成趋势线,但很多场景下我们只需要主面板保留趋势线。

问题复现

先生成模拟数据:

np.random.seed(42)
data = pd.DataFrame(np.random.randint(0, 100, (100, 4)), columns=["feature1", "feature2", "feature3", "feature4"])
data["label"] = np.random.choice(list("ABC"), 100)
data["is_outlier"] = np.random.choice([True, False], 100)

创建包含边缘分布和趋势线的散点图:

fig = px.scatter(
    data, x="feature1", y="feature2",
    color="label", symbol="is_outlier", symbol_map={True: "x", False: "circle"},
    marginal_x="box", marginal_y="box",
    trendline="ols", trendline_scope="overall", trendline_color_override='black',
)

此时主面板、顶部x边缘面板、右侧y边缘面板都会显示趋势线,且直接删除末尾两个趋势线trace会导致图例中的趋势线标识消失。

更简洁的解决方案

不需要依赖固定索引操作fig.data,而是通过trace的轴属性和名称来精准筛选:

  1. 找到主面板的趋势线,将其showlegend设为True(确保图例保留)
  2. 过滤掉边缘面板的趋势线trace

代码实现:

# 配置主趋势线显示图例
for trace in fig.data:
    if trace.name == "trendline" and trace.xaxis == "x" and trace.yaxis == "y":
        trace.showlegend = True

# 移除边缘面板的趋势线
fig.data = [trace for trace in fig.data if not (
    trace.name == "trendline" and (trace.xaxis == "x2" or trace.yaxis == "y2")
)]

fig.show()

完整可运行代码

import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio

pio.renderers.default = "browser"

# 生成模拟数据
np.random.seed(42)
data = pd.DataFrame(np.random.randint(0, 100, (100, 4)), columns=["feature1", "feature2", "feature3", "feature4"])
data["label"] = np.random.choice(list("ABC"), 100)
data["is_outlier"] = np.random.choice([True, False], 100)

# 创建带边缘分布和趋势线的图表
fig = px.scatter(
    data, x="feature1", y="feature2",
    color="label", symbol="is_outlier", symbol_map={True: "x", False: "circle"},
    marginal_x="box", marginal_y="box",
    trendline="ols", trendline_scope="overall", trendline_color_override='black',
)

# 处理趋势线:保留主面板,移除边缘面板
for trace in fig.data:
    if trace.name == "trendline" and trace.xaxis == "x" and trace.yaxis == "y":
        trace.showlegend = True
fig.data = [trace for trace in fig.data if not (trace.name == "trendline" and (trace.xaxis == "x2" or trace.yaxis == "y2"))]

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:35:03