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

如何在Plotly中默认隐藏或显示指定颜色的图表系列?

Plotly 折线图默认显示/隐藏指定系列的实现

问题解答

  1. 可以在显示图表时默认选择显示或隐藏指定系列(比如只显示type=0和type=1的系列)。
  2. 完全不需要修改DataFrame,仅通过调整Plotly的图表设置就能实现。

具体实现代码

在你现有代码的基础上,只需在创建fig之后、调用fig.show()之前,添加一段修改trace可见性的代码即可:

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

N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N) + 5
random_y1 = np.random.randn(N)
random_y2 = np.random.randn(N) - 5

df_all = pd.DataFrame()

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y0
df['type'] = np.full(len(random_x), 0)
df_all = pd.concat([df_all, df], axis=0)

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y1
df['type'] = np.full(len(random_x), 1)
df_all = pd.concat([df_all, df], axis=0)

df = pd.DataFrame()
df['x']    = random_x
df['y']    = random_y2
df['type'] = np.full(len(random_x), 2)
df_all = pd.concat([df_all, df], axis=0)

# 创建图表
fig = px.line(x=df_all['x'], y=df_all['y'], color=df_all['type'])

# 修改指定系列的可见性:默认隐藏type=2的系列
for trace in fig.data:
    # trace.name对应type的值,注意是字符串格式
    if trace.name == '2':
        # 设置为legendonly:默认不显示,但可通过图例手动开启
        trace.visible = 'legendonly'

fig.show()

关键说明

  • Plotly生成的每个折线系列对应fig.data中的一个trace对象,每个trace的name属性就是你设置的type值(注意是字符串类型)。
  • visible属性有三种取值:
    • True:默认显示该系列
    • 'legendonly':默认隐藏,但可以通过点击图例重新显示
    • False:完全隐藏,图例中也无法切换显示状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:20:43