我正在尝试使用 go.bar 制作子图条形图。我想通过分类材料变量为条形着色。我已经做到了这一点,但也希望子图之间有一个共享图例,按材质显示颜色。
materials=['food', 'flowers', 'chess', 'garden', 'kitchen']
x=['browns', 'highes', 'jacks', 'johns', 'harrys']
y=[1,3,5,6,7]
x2=['trevors', 'elens', 'georges', 'marias', 'franks']
y2=[3,7,8,9,5]
fig = make_subplots(rows=3, cols=1)
color_map = {'food':'red',
'flowers':'blue',
'chess':'yellow',
'garden':'green',
'kitchen':'grey'}
colors = [color_map[category] for category in materials]
fig.add_trace(
go.Bar(x=x,
y=y,
# name=materials,
marker_color=colors),
row=1, col=1
)
fig.add_trace(
go.Bar(x=x2,
y=y2,
# name=materials,
marker_color=colors),
row=2, col=1
)
fig.show()
如何获得图例来显示条形是按材料着色的?
如果您想按每种材料的颜色对图例进行分类,则需要使用为每种材料绘制图表的过程。图例将显示具有相同图例名称的上图的图例和下图的图例。在此状态下单击图例将在图表中显示或隐藏它。具有相同的图例可能会引起混乱。为了避免这种情况,可以对图例进行分组。还有一种方法可以删除重复的图例。 我们不知道您的最终目标是什么,因此请尝试添加分组或删除重复的图例。每个分组和删除重复项的代码都带有注释,以便您可以解锁并检查结果。
import plotly.graph_objects as go
from plotly.subplots import make_subplots
materials=['food', 'flowers', 'chess', 'garden', 'kitchen']
x=['browns', 'highes', 'jacks', 'johns', 'harrys']
y=[1,3,5,6,7]
x2=['trevors', 'elens', 'georges', 'marias', 'franks']
y2=[3,7,8,9,5]
fig = make_subplots(rows=3, cols=1)
color_map = {'food':'red',
'flowers':'blue',
'chess':'yellow',
'garden':'green',
'kitchen':'grey'}
colors = [color_map[category] for category in materials]
for i in range(len(materials)):
fig.add_trace(go.Bar(x=[x[i]],
y=[y[i]],
name=materials[i],
# legendgroup='group1',
# legendgrouptitle=dict(text='Materials'),
marker_color=colors[i]),
row=1, col=1
)
fig.add_trace(go.Bar(x=[x2[i]],
y=[y2[i]],
name=materials[i],
# legendgroup='group2',
# legendgrouptitle=dict(text='Materials'),
marker_color=colors[i]),
row=2, col=1)
# Removal of duplicate legends.
# names = set()
# fig.for_each_trace(
# lambda trace:
# trace.update(showlegend=False)
# if (trace.name in names) else names.add(trace.name))
fig.show()