Plotly下拉按钮切换XY变量后图例年份筛选功能失效问题咨询
问题原因
你的代码核心问题出在下拉按钮的update参数配置上:你初始化了2020、2021两个独立的散点trace,但切换X/Y轴的按钮更新数据时,传入的是全量df的列数据,直接覆盖了两个trace的原始数据结构,把两个独立trace合并成了全量数据,自然就失去了按年份筛选的能力。另外原代码还存在button_y_list的append逻辑缩进错误,只会生成最后一个变量的Y轴切换按钮。
修复方案
- 切换X轴时,传入的x值要分别对应2020、2021两个子数据集的对应列,顺序和初始化trace的顺序保持一致
- 切换Y轴时同理,y值也要分两个年份的子数据集传入
- marker颜色映射也要对应各自年份的子数据集,不要用全量df的
- 修正Y轴按钮生成的缩进错误
修复后的完整代码
import plotly.graph_objects as go import pandas as pd # 提前拆分好两年的数据,避免重复计算 data_2020 = df[df.index.year==2020] data_2021 = df[df.index.year==2021] button_x_list = [] button_y_list = [] colors = {"A": "red", "B": "blue", "C": "yellow"} for col in colnames: button_x_list.append( dict( method="update", label=col, args=[ # 按trace顺序分别传2020、2021的x值 {"x": [data_2020[col], data_2021[col]]}, {"xaxis": {"title": col}}, # 按trace顺序分别传对应年份的marker颜色 {"marker":{"color": [list(data_2020["status"].map(colors)), list(data_2021["status"].map(colors))]}}, ], ) ) # 修正缩进,Y轴按钮生成逻辑放在循环内 button_y_list.append( dict( method="update", label=col, args=[ # 按trace顺序分别传2020、2021的y值 {"y": [data_2020[col], data_2021[col]]}, {"yaxis": {"title": col}}, {"marker":{"color": [list(data_2020["status"].map(colors)), list(data_2021["status"].map(colors))]}}, ], ) ) button_x_dict = dict( direction="down", showactive=True, xanchor="left", yanchor="top", visible=True, buttons=button_x_list, pad={"r": 15, "t": 10}, x=0.27, y=1.07, ) button_y_dict = dict( direction="down", showactive=True, xanchor="left", yanchor="top", visible=True, buttons=button_y_list, pad={"r": 15, "t": 10}, x=0.5, y=1.07, ) annotation_x = dict( text="X:", showarrow=False, x=0.25, y=1.05, xanchor="left", xref="paper", yref="paper", align="left", yanchor="top", ) annotation_y = dict( text="Y:", showarrow=False, x=0.48, y=1.05, xanchor="left", xref="paper", yref="paper", align="left", yanchor="top", ) # 修正初始化时marker颜色的数据源,用对应年份的子数据集 fig = go.Figure(go.Scatter(x=data_2020["3"], y=data_2020["3"], mode="markers", marker={"color":data_2020["status"].map(colors)},name="2020")) fig.add_trace(go.Scatter(x=data_2021["3"], y=data_2021["3"], mode="markers", marker={"color":data_2021["status"].map(colors)},name="2021")) fig.update_layout( updatemenus=[button_x_dict, button_y_dict], annotations=[annotation_x, annotation_y], title="Test", xaxis={"title":"3"}, yaxis={"title":"3"} ) fig.show()
内容的提问来源于stack exchange,提问作者JPV
相关产品推荐
相关产品推荐

