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 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

最佳答案

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

引用: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中显示。

关于python - 如何避免 plotly 中的重复图例标签或传递自定义图例标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26939121/

相关文章:

循环内带有默认参数的 Python 函数

javascript - 在 javascript 中制作 plotly 树状图

python - 将 RGB 颜色转换为 RGBA 的 Plotly 函数? (Python)

python - Plotly 图形组件无法接受视口(viewport)单位来设置文本注释字体大小

Python Telegram 机器人 - 发送图像

Python输入限制和重新提升

python - 对屏蔽数组的有效值调用函数

python - 在条形图上的 Plotly Express 中更改轴/图例名称

javascript - 如何删除plotly.js 图表轴中的非整数?

python - 来自大型掩码数组的 Numpy 平均值