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

Plotly Express折线图仅显示部分标记点的实现方法

Plotly高分辨率折线图仅显示部分分类标记的解决方案

可以通过两种核心方法实现保留折线高分辨率的同时,只显示部分分类标记,无需删除原始数据点:

方法1:拆分折线与标记为两个独立轨迹

用全量数据绘制折线(无标记),再从原始数据中采样部分点单独绘制分类标记,两者叠加即可。这种方式能灵活控制折线和标记的样式,适合需要区分折线与标记视觉效果的场景。

示例代码:

import plotly.graph_objects as go
import numpy as np

# 生成模拟高分辨率数据
x = np.linspace(0, 10, 1000)
y = np.sin(x)
# 模拟分类标签(每100个点切换一个类别)
category = np.repeat(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], 100)

# 采样标记点:每隔50个点取一个(可根据需求调整采样规则,比如按类别取首尾点)
sample_indices = np.arange(0, len(x), 50)
x_sample = x[sample_indices]
y_sample = y[sample_indices]
category_sample = category[sample_indices]

# 定义类别到符号的映射
cat_symbol_map = {
    'A': 'circle', 'B': 'square', 'C': 'diamond',
    'D': 'cross', 'E': 'x', 'F': 'triangle-up',
    'G': 'triangle-down', 'H': 'triangle-left',
    'I': 'triangle-right', 'J': 'star'
}
# 转换采样点的类别为对应符号
sample_symbols = [cat_symbol_map[cat] for cat in category_sample]

# 创建图表
fig = go.Figure()
# 添加全量折线(仅线条,无标记)
fig.add_trace(go.Scatter(
    x=x, y=y,
    mode='lines',
    line=dict(color='steelblue'),
    name='高分辨率折线'
))
# 添加采样后的分类标记(仅标记,无线条)
fig.add_trace(go.Scatter(
    x=x_sample, y=y_sample,
    mode='markers',
    marker=dict(size=8, symbol=sample_symbols, color='crimson'),
    name='分类标记'
))

fig.update_layout(title='高分辨率折线+稀疏分类标记', xaxis_title='X轴', yaxis_title='Y轴')
fig.show()

方法2:单轨迹内设置稀疏标记

直接在同一条折线轨迹中,通过自定义symbol数组实现——将大部分点的标记设为none,仅采样点设置对应分类符号。这种方式更简洁,适合折线与标记样式关联度高的场景。

示例代码:

import plotly.graph_objects as go
import numpy as np

# 生成模拟高分辨率数据
x = np.linspace(0, 10, 1000)
y = np.sin(x)
category = np.repeat(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], 100)

# 构建符号数组:默认全部为无标记,仅采样点设置对应符号
symbol_array = ['none'] * len(x)
sample_indices = np.arange(0, len(x), 50)
cat_symbol_map = {
    'A': 'circle', 'B': 'square', 'C': 'diamond',
    'D': 'cross', 'E': 'x', 'F': 'triangle-up',
    'G': 'triangle-down', 'H': 'triangle-left',
    'I': 'triangle-right', 'J': 'star'
}
# 为采样点赋值对应符号
for idx in sample_indices:
    symbol_array[idx] = cat_symbol_map[category[idx]]

# 单轨迹实现折线+稀疏标记
fig = go.Figure(go.Scatter(
    x=x, y=y,
    mode='lines+markers',
    line=dict(color='steelblue'),
    marker=dict(size=8, symbol=symbol_array, color='crimson'),
    name='折线+稀疏分类标记'
))

fig.update_layout(title='单轨迹稀疏标记示例', xaxis_title='X轴', yaxis_title='Y轴')
fig.show()

采样规则说明

采样点的选择可以根据需求灵活调整:

  • 固定间隔采样(如每隔N个点取一个)
  • 按分类采样(每个类别取首尾点、峰值点或随机点)
  • 基于X轴范围采样(如每0.5个X单位取一个点)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:39:28