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

Plotly带子图与下拉菜单图表:非默认选项下第二子图消失的修复

问题:Plotly下拉菜单切换时第二个子图消失

我用Plotly生成了包含两个子图和下拉菜单的图表,默认选项显示正常,但切换其他选项时第二个子图会消失,怎么修复才能让所有选项选中时第二子图和图例都正常显示?

问题原因

问题出在下拉按钮的visible参数配置上:当前代码中,visible列表仅覆盖了第一个子图的3个trace(对应Value3、Value4、Value5),但第二个子图的trace是第4个(索引3)。切换下拉选项时,Plotly会将未在visible列表中指定的trace默认设为不可见,导致第二个子图消失。

修复方案

需要给每个下拉按钮的visible列表追加一个True,确保第二个子图的trace始终保持可见;同时为每个trace添加name参数,让图例正常显示。

修复后的完整代码

import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
np.random.seed(42)

data = {
'Value1': np.random.randint(1, 1000, 100),
'Value2': np.random.randint(1, 1000, 100),
'Value3': np.random.randint(1, 1000, 100),
'Value4': np.random.randint(1, 1000, 100),
'Value5': np.random.randint(1, 1000, 100),
'Value6': np.random.randint(1, 1000, 100),
}

df = pd.DataFrame(data)

fig = make_subplots(rows = 2, cols = 1, vertical_spacing = 0.1, shared_xaxes = True)

# 添加第一个子图的trace,指定名称用于图例显示
for r in df.columns[2:-1]:
    fig.add_trace(go.Scatter(
        x = df['Value1'], 
        y = df[r], 
        mode ='markers', 
        marker_symbol = 'circle', 
        visible = False,
        name=r
    ), row = 1, col = 1, secondary_y = False)

# 默认显示第一个子图的第一个trace
fig.data[0].visible = True

# 修复下拉按钮:每个visible列表追加True,确保第二个子图始终可见
dropdown_buttons = [
    {
        'label': column, 
        'method': 'update', 
        'args': [
            {'visible': [col == column for col in df.columns[2:-1]] + [True]}
        ]
    } 
    for column in df.columns[2:-1]
]

# 添加第二个子图的trace,指定名称用于图例显示
fig.add_trace(go.Scatter(
    x = df['Value1'], 
    y = df['Value2'], 
    mode = 'markers', 
    visible = True,
    name='Value2'
), row = 2, col = 1, secondary_y = False)

fig.update_xaxes(title_text = 'Value1', row = 2, col = 1)
fig.update_layout(
    updatemenus=[{'buttons': dropdown_buttons, 'direction': 'down', 'showactive': True}],
    template = 'plotly'
)
fig.write_html('plot.html')

额外优化说明

  • 将showactive设为True,可以在下拉菜单中高亮当前选中的选项,提升用户体验;
  • 为每个trace添加name参数,确保图例能正确显示各系列名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:32:33