如何在Plotly折线图中选择性隐藏部分线条的图例?
解决方案
你可以在添加不需要显示图例的灰色线条trace时,直接设置showlegend=False参数即可,Plotly支持对单条trace单独控制是否展示图例,不需要全局控制图例显隐。
修改后的代码如下:
import plotly.graph_objects as go fig = go.Figure() fig.update_layout(autosize=False, width=800, height=500, template='none') fig.update_layout(title = 'Title', xaxis_title = 'Games', yaxis_title = 'Profit') for team in rest_teams: # 灰色线条添加showlegend=False隐藏对应图例 fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = {'color': '#F5F5F5'}, showlegend=False)) for team in big_eight: line_dict = {'color': cmap[team]} # 彩色线条保留默认showlegend=True,正常展示图例 fig.add_traces(go.Scatter(x=df['x'], y = df[team], name = team, line = line_dict)) fig.show()
如果你的trace已经全部添加完成,不想修改添加逻辑,也可以通过批量修改trace属性的方式实现:
# 遍历所有trace,将颜色为浅灰色的trace图例隐藏 for trace in fig.data: if trace.line.color == '#F5F5F5': trace.showlegend = False
内容的提问来源于stack exchange,提问作者Ravi
相关产品推荐
相关产品推荐

