Plotly:在plotly 离线浏览器图中选择下拉菜单选项时无法更新图例

问题描述 投票:0回答:1

我正在尝试使用离线浏览器绘图通过下拉菜单选项更新绘图。该代码运行良好,但是当选择菜单选项时,每个跟踪的图例不会更新。 对于所有痕迹选项,我可以看到所有 3 个图例。然而,对于其余的痕迹图例没有得到更新/根本没有显示。

** 我尝试单独设置图例的可见性。使用了“方法”:“更新”和“方法”:“重新设计”。似乎没有任何作用。**

import numpy as np
import pandas as pd
import plotly.graph_objs as go
from plotly.offline import plot

# Sample data
x = np.linspace(0, 10, 100)  # X axis
y1 = np.sin(x)  # red trace
y2 = np.cos(x)  # blue trace
y3 = np.sin(x) + np.cos(x)  # green trace

# Convert sample data to pandas DataFrame
data_df = pd.DataFrame({'X': x, 'Red': y1, 'Blue': y2, 'Green': y3})

# Define the layout of the plot
layout = go.Layout(
    title='Plot with Dropdown Menu',
    xaxis=dict(title='X-axis Title'),
    yaxis=dict(title='Y-axis Title')
)

# Create an empty figure
fig = go.Figure(layout=layout)

# Define dropdown menu options
dropdown_options = [
    {'label': 'Option 1', 'value': 'all_visible'},   # all traces visible option
    {'label': 'Option 2', 'value': 'red_visible'},   # only red trace visible option
    {'label': 'Option 3', 'value': 'blue_visible'},  # only blue trace visible option
    {'label': 'Option 4', 'value': 'green_visible'}  # only green trace visible option
]

buttons = []

for option in dropdown_options:
    args = [{'visible': [False] * len(data_df.columns)}]
    legend_visibility = [True] * len(data_df.columns)  # Initialize legend visibility list
     
    if option['value'] == 'red_visible':
        args[0]['visible'][0] = True
        legend_visibility[1:] = [True] * (len(data_df.columns) - 1)  # Set legend visibility for visible traces
        
    elif option['value'] == 'blue_visible':
        args[0]['visible'][2] = True
        legend_visibility[2] = True
        
    elif option['value'] == 'green_visible':
        args[0]['visible'][0] = True
        legend_visibility[0] = True
        
    elif option['value'] == 'all_visible':
        args[0]['visible'] = [True] * len(data_df.columns)
        legend_visibility[1:] = [True] * (len(data_df.columns) - 1)  # Set legend visibility for visible traces

    # Set legend visibility for each trace
    for i, trace in enumerate(fig.data):
        if i < len(legend_visibility):
            trace.visible = legend_visibility[i]

    button = {'method': 'update', 'label': option['label'], 'args': args}
    buttons.append(button)

updatemenus = [{'buttons': buttons, 'direction': 'down', 'showactive': True}]
fig.update_layout(updatemenus=updatemenus)

# Add traces to the figure
for column_name in data_df.columns:
    if column_name != 'X':
        trace = go.Scatter(x=data_df['X'], y=data_df[column_name], mode='lines', name=column_name, visible=False)
        fig.add_trace(trace)

plot(fig)
python plotly
1个回答
0
投票

我的修改是在初始图表中显示图例。这将允许为每个选择显示图例。第一种颜色中线条颜色默认为蓝色,因此在创建图表时,将列名称小写并将其指定为线条颜色。这将匹配初始图形和相应的线条颜色。

  • 显示图例
# Create an empty figure
fig = go.Figure(layout=layout)

# Show legend 
fig.update_layout(showlegend=True)
  • 线条颜色更新
# Add traces to the figure
for column_name in data_df.columns:
    if column_name != 'X':
        trace = go.Scatter(x=data_df['X'],
                           y=data_df[column_name],
                           mode='lines',
                           name=column_name,
                           line=dict(color=column_name.lower()), # line color setting
                           visible=False
                          )
        fig.add_trace(trace)

© www.soinside.com 2019 - 2024. All rights reserved.