如何用Plotly Graph Objects在单柱状图迹中添加多纹理图例标记
单条Plotly柱状图迹实现自定义双图例(含纹理)
需求说明
现有如下Plotly代码生成的柱状图:
import plotly.graph_objects as go x=[1,2,3,4] y=[2,2,4,3] colors = ["blue","blue","orange","blue"] textures = ["","","x",""] myfig = go.Figure() myfig.add_trace(go.Bar(x=x ,y=y ,showlegend=True ,marker_color=colors ,marker_pattern_shape=textures ,name="my_trace")) myfig.show()
生成的图表样式:
包含4个柱状,其中第1、2、4个为蓝色无纹理,第3个为橙色带“x”纹理的柱状图
需要在不新增图迹的前提下,让图例显示两个自定义项:
- 蓝色柱状对应名称“any”
- 带“x”纹理的橙色柱状对应名称“max”,且图例项需显示对应纹理
解决方案
通过手动自定义图例的items属性,将两个图例项关联到同一条图迹,分别指定颜色、纹理和标签,即可实现需求:
import plotly.graph_objects as go x=[1,2,3,4] y=[2,2,4,3] colors = ["blue","blue","orange","blue"] textures = ["","","x",""] myfig = go.Figure() myfig.add_trace(go.Bar( x=x, y=y, showlegend=True, marker_color=colors, marker_pattern_shape=textures )) # 自定义图例项,关联到同一条图迹(traceindex=0) myfig.update_layout( legend={ "items": [ { "traceindex": 0, "label": "any", "color": "blue", "pattern_shape": "" }, { "traceindex": 0, "label": "max", "color": "orange", "pattern_shape": "x" } ] } ) myfig.show()
关键说明
legend.items中的每个元素都指定traceindex=0,表示都关联到唯一的那条柱状图迹- 分别为两个图例项设置对应的
color和pattern_shape,保证图例样式与对应柱状的样式一致 - 无需新增任何图迹,仅通过布局配置实现双图例需求
内容的提问来源于stack exchange,提问作者33fred33
相关产品推荐
相关产品推荐

