Python 如何避免在plotly中重复图例标签或传递自定义图例标签
如何避免子批次中出现重复的图例标签?在matplotlib中,一种方法是将自定义图例标签传递给图例对象。我在plotly中找不到任何等效选项的文档。有什么想法吗Python 如何避免在plotly中重复图例标签或传递自定义图例标签,python,plotly,Python,Plotly,如何避免子批次中出现重复的图例标签?在matplotlib中,一种方法是将自定义图例标签传递给图例对象。我在plotly中找不到任何等效选项的文档。有什么想法吗 traces = [] colors = {'Iris-setosa': 'rgb(31, 119, 180)', 'Iris-versicolor': 'rgb(255, 127, 14)', 'Iris-virginica': 'rgb(44, 160, 44)'} for col i
traces = []
colors = {'Iris-setosa': 'rgb(31, 119, 180)',
'Iris-versicolor': 'rgb(255, 127, 14)',
'Iris-virginica': 'rgb(44, 160, 44)'}
for col in range(4):
for key in colors:
traces.append(Histogram(x=X[y==key, col],
opacity=0.75,
xaxis='x%s' %(col+1),
marker=Marker(color=colors[key]),
name=key
)
)
data = Data(traces)
layout = Layout(barmode='overlay',
xaxis=XAxis(domain=[0, 0.25], title='sepal length (cm)'),
xaxis2=XAxis(domain=[0.3, 0.5], title='sepal width (cm)'),
xaxis3=XAxis(domain=[0.55, 0.75], title='petal length (cm)'),
xaxis4=XAxis(domain=[0.8, 1], title='petal width (cm)'),
yaxis=YAxis(title='count'),
title='Distribution of the different Iris flower features')
fig = Figure(data=data, layout=layout)
py.iplot(fig)
在跟踪级别上对此进行绘图控制。尝试在
直方图中输入您不希望出现在图例中的showlegdeng=False
参考:
例如:
从上面的链接直接复制粘贴
import plotly.plotly as py
from plotly.graph_objs import *
# Fill in with your personal username and API key
# or, use this public demo account
py.sign_in('Python-Demo-Account', 'gwt101uhh0')
trace1 = Scatter(
x=[0, 1, 2],
y=[1, 2, 3],
name='First Trace',
showlegend=False
)
trace2 = Scatter(
x=[0, 1, 2, 3],
y=[8, 4, 2, 0],
name='Second Trace',
showlegend=True
)
data = Data([trace1, trace2])
plot_url = py.plot(data, filename='show-legend')
您要查看的用法显示在上面的trace1
中。更好的方法:
将legendgroup
选项设置为每个轨迹所需的图例标签。
这将允许您过滤同一组中的所有内容
使用showlegend=False
选项隐藏其余记录道的图例
这将提供您想要的确切行为
旧解决方案(不推荐):
另一种解决方案是添加“虚拟”跟踪并隐藏数据,但只显示图例。
使用这种方法,您无法对任何数据进行切片(这不是一件坏事)
这是我提出的一个代码片段,它避免了在每个具有重复的名称的跟踪上手动设置showlegend=False
names = set()
fig.for_each_trace(
lambda trace:
trace.update(showlegend=False)
if (trace.name in names) else names.add(trace.name))
fig.for_每个_跟踪
为每个跟踪调用传递的函数。该函数跟踪已出现的图例名称(通过设置名称
,如注释中建议的@LucG),并隐藏重复(或三次,…)名称的图例条目
代码需要在将所有跟踪添加到图形后运行,然后再运行show
n.@SebastianRaschka,但如果trace1
的图例被隐藏,则无法控制或隐藏trace1
的跟踪。如果需要在循环中生成绘图,您可以使用set
来跟踪已将哪个跟踪名称添加到图形中,然后如果tracename不在set中,则使用showlegdeng=True\u tracenames else False
我不明白如何使用legendgroup
。你能详细说明一下吗?看看https://plotly.com/python/legend/#grouped-legend
@A.Donda如果您想过滤掉属于某个图例的数据,使用showlegdend=False
将只过滤掉部分数据,因为另一部分的图例是隐藏的。但是如果使用legendgroup
,过滤掉图例中显示的零件也会过滤掉隐藏的零件,因为它们位于同一图例组中
names = set()
fig.for_each_trace(
lambda trace:
trace.update(showlegend=False)
if (trace.name in names) else names.add(trace.name))