如何为下拉菜单中所有Plotly箱线图应用color='sex'参数?
Plotly箱线图下拉切换时着色失效的解决方法
用Plotly绘制箱线图时,设置下拉菜单切换G1、G2、G3的显示状态,仅初始的G1、G2、G3联合图能按dataframe的sex字段着色区分,切换到G2或G3单独图时,箱线图无法显示sex对应的颜色效果。原代码如下:
dropdown_buttons = [{'label':'G1, G2, G3', 'method': 'update', 'args':[{'visible': [True, True, True]}, {'title': 'G1, G2, G3'}]}, {'label':'G1', 'method': 'update', 'args':[{'visible': [True, False, False]}, {'title': 'G1'}]}, {'label':'G2', 'method': 'update', 'args':[{'visible': [False, True, False]}, {'title': 'G2'}]}, {'label':'G3', 'method': 'update', 'args':[{'visible': [False, False, True]}, {'title': 'G3'}]}, ] fig5 = go.Figure(px.box(students, x='age', y=['G1', 'G2', 'G3'], color = 'sex', labels = {'age': 'Age', 'G3': 'G3', 'sex': 'Sex'})) fig5.update_layout({'updatemenus':[{'type': "dropdown", 'x': 1.3, 'y': 0.5, 'showactive': True, 'active': 0, 'buttons': dropdown_buttons}]}) fig5.show()
问题原因
你用px.box(students, x='age', y=['G1', 'G2', 'G3'], color='sex')生成的图表,实际包含6个trace——每个科目(G1/G2/G3)对应sex的两个类别(如男/女),各占一个trace。但原下拉菜单的visible参数只设置了3个布尔值,仅控制了每个科目的第一个trace的显示状态,导致切换时其他性别的trace被隐藏,自然看不到着色效果。
解决方法
修改下拉菜单的visible参数,对应6个trace的显示状态:
- 联合显示:所有6个trace都可见
- 显示G1:仅前2个trace(G1的两个性别)可见
- 显示G2:仅中间2个trace(G2的两个性别)可见
- 显示G3:仅最后2个trace(G3的两个性别)可见
修改后的完整代码:
dropdown_buttons = [ {'label':'G1, G2, G3', 'method': 'update', 'args':[{'visible': [True]*6}, {'title': 'G1, G2, G3'}]}, {'label':'G1', 'method': 'update', 'args':[{'visible': [True, True, False, False, False, False]}, {'title': 'G1'}]}, {'label':'G2', 'method': 'update', 'args':[{'visible': [False, False, True, True, False, False]}, {'title': 'G2'}]}, {'label':'G3', 'method': 'update', 'args':[{'visible': [False, False, False, False, True, True]}, {'title': 'G3'}]}, ] fig5 = go.Figure(px.box(students, x='age', y=['G1', 'G2', 'G3'], color = 'sex', labels = {'age': 'Age', 'G3': 'G3', 'sex': 'Sex'})) fig5.update_layout({ 'updatemenus':[{ 'type': "dropdown", 'x': 1.3, 'y': 0.5, 'showactive': True, 'active': 0, 'buttons': dropdown_buttons }] }) fig5.show()
内容的提问来源于stack exchange,提问作者LC0223
相关产品推荐
相关产品推荐

