Plotly中隐藏重复图例问题求助
解决Plotly按钮切换图表时的图例重复问题
你的代码存在两个核心问题:一是没有将柱状图和折线图的轨迹合并到同一个Figure对象中;二是使用restyle修改type的方式会让所有轨迹强制切换类型并同时显示,最终导致图例重复。以下是修复后的代码:
import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objects as go # 数据处理部分保持不变 url = "https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv" alloy = pd.read_csv(url) del alloy['temper'] alloy = alloy.rename(columns={ 'aluminum_alloy':'Alloy Number', 'modulus_elastic': 'Elastic Modulus', 'modulus_shear': 'Shear Modulus', 'strength_yield': 'Yield Strength', 'strength_tensile': 'Tensile Strength' }) # 生成柱状图和折线图的轨迹对象 bar_fig = px.bar( alloy, x = "Alloy Number", y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"], barmode = 'group', width = 1100, height =500, color_discrete_sequence = px.colors.qualitative.Pastel, labels={"value": "Data Values"}, template = 'seaborn' ) line_fig = px.line( alloy, x = "Alloy Number", y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"], width = 1100, height =500, color_discrete_sequence = px.colors.qualitative.Pastel, labels={"value": "Data Values"}, template = 'seaborn' ) # 创建空的Figure,合并两种图表的轨迹 fig = go.Figure() # 添加柱状图轨迹,默认可见,设置统一的图例组 for trace in bar_fig.data: trace.legendgroup = trace.name # 用指标名称作为图例组 trace.showlegend = True fig.add_trace(trace) # 添加折线图轨迹,默认隐藏,匹配柱状图的图例组 for trace in line_fig.data: trace.legendgroup = trace.name trace.visible = False trace.showlegend = False # 折线图轨迹不单独显示图例 fig.add_trace(trace) # 更新布局,添加切换按钮 fig.update_layout( updatemenus=[ dict( type = "buttons", direction = "left", buttons=list([ dict( args=[{'visible': [True]*4 + [False]*4}], # 显示前4个柱状图轨迹,隐藏后4个折线图轨迹 label="柱状图", method="update", ), dict( args=[{'visible': [False]*4 + [True]*4}], # 隐藏前4个柱状图轨迹,显示后4个折线图轨迹 label="折线图", method="update" ) ]), pad={"r": 10, "t": 10}, showactive=True, x=0.11, xanchor="left", y=1.1, yanchor="middle" ), ] ) fig.show()
关键修改说明:
- 合并轨迹:创建空Figure后,分别添加柱状图和折线图的所有轨迹,避免两个独立图表的冲突。
- 图例组匹配:让柱状图和对应指标的折线图使用相同的
legendgroup,确保图例切换时保持一致性。 - 可见性控制:按钮通过
update方法直接控制对应轨迹的显示/隐藏,替代原来修改type的错误方式,从根本上解决图例重复问题。 - 图例显示优化:仅让柱状图轨迹显示图例,折线图轨迹不单独生成图例,避免重复。
内容的提问来源于stack exchange,提问作者Lynman Alpha
相关产品推荐
相关产品推荐

