Plotly子图条形图图例配置:按动物类别而非Trace生成
解决Plotly子图条形图图例按动物类别展示的问题
当前代码中每个子图是一个包含三种动物的Trace,导致图例对应每个子图而非动物类别。要实现按动物类别生成图例,需要将每个动物作为独立Trace添加到对应子图中,并统一设置相同的名称和颜色,同时控制图例的显示逻辑:
修改后的代码
import plotly.graph_objects as go from plotly.subplots import make_subplots # 定义动物类别、对应颜色和各动物园的数据 animals = ['giraffes', 'orangutans', 'monkeys'] colors = ["#00573C", '#9BD7BE', '#990012'] zoo_data = [ [21, 15, 23], # Zoo1数据 [15, 31, 23], # Zoo2数据 [11, 32, 23] # Zoo3数据 ] # 创建子图 fig = make_subplots(rows=1, cols=3, subplot_titles=('Zoo1', 'Zoo2', 'Zoo3')) # 遍历每个动物园,为每个动物添加独立Trace for col_idx, zoo_vals in enumerate(zoo_data, start=1): for animal_idx, (animal, color, val) in enumerate(zip(animals, colors, zoo_vals)): # 只有第一个子图的Trace显示图例,避免重复 show_legend = (col_idx == 1) fig.add_trace( go.Bar( y=[animal], x=[val], orientation='h', marker_color=color, name=animal, # 统一设置动物名称作为Trace名称 showlegend=show_legend ), row=1, col=col_idx ) fig.update_layout( legend_title_text='动物类别', height=400, width=800 ) fig.show()
关键调整点
- 将每个动物拆分为独立的
go.BarTrace,而非在单个Trace中包含所有动物 - 为同一动物的所有Trace设置相同的name,Plotly会自动合并同名Trace的图例
- 通过
showlegend参数控制仅第一个子图的Trace显示图例,避免图例重复 - 统一使用预定义的颜色映射,确保同一动物在所有子图中颜色一致
内容的提问来源于stack exchange,提问作者codedancer
相关产品推荐
相关产品推荐

