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的轴属性和名称来精准筛选:
- 找到主面板的趋势线,将其
showlegend设为True(确保图例保留) - 过滤掉边缘面板的趋势线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
相关产品推荐
相关产品推荐

