如何在plotly中避免重复的图例标签或传递自定义图例标签

时间:2014-11-14 21:24:58

标签: 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 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)

enter image description here

3 个答案:

答案 0 :(得分:3)

在跟踪级别上进行Plotly控制。尝试在showlegend=False内部传递您不希望出现在图例中的Histogram痕迹。

参考:https://plot.ly/python/reference/#Histogram-showlegend

示例:https://plot.ly/python/legend/#Hiding-Legend-Entries

从上面的链接直接复制粘贴。

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

答案 1 :(得分:1)

更好的方法:

legendgroup选项设置为每个跟踪所需的图例标签。 这将允许您过滤同一组中的所有内容。

隐藏剩余的痕迹'使用showlegend=False选项的图例。

这将提供您想要的确切行为。

旧解决方案(不推荐):

通过添加" dummy"还有另一种解决方案。跟踪和隐藏数据但仅显示图例。 使用此方法,您无法对任何数据进行切片(这不是一件坏事)。

trace_dummy = Scatter(
    x=[0, 0, 0], # Data is irrelevant since it won't be shown
    y=[0, 0, 0],
    name='Whatever Trace',
    showlegend=True,
    visible="legendonly"
)

答案 2 :(得分:0)

这是我想到的代码段,避免了在每个跟踪上手动设置showlegend=False并重复name

names = set()
fig.for_each_trace(
    lambda trace:
        trace.update(showlegend=False)
        if (trace.name in names) else names.add(trace.name))

fig.for_each_trace为每个跟踪调用传递的函数。该功能跟踪(已通过names集,例如在注释中建议的@LucG)已出现的图例名称,并隐藏图例条目以提供重复(或三倍的...)名称。

代码需要在所有痕迹都添加到图中之后并且在show n之前运行。

相关问题