简体   繁体   English

在python中绘制带有图例的垂直线

[英]Plotly vertical line with legend in python

In plotly website, there is example that can use shape function add vertical or horizontal line in plotly.在 plotly 网站中,有示例可以使用shape函数在 plotly 中添加垂直或水平线。

import plotly.plotly as py
import plotly.graph_objs as go

trace0 = go.Scatter(
    x=[2, 3.5, 6],
    y=[1, 1.5, 1],
    mode='text',
)
data = [trace0]
layout = {
    'xaxis': {
        'range': [0, 7]
    },
    'yaxis': {
        'range': [0, 2.5]
    },
    'shapes': [
        # Line Horizontal
        {
            'type': 'line',
            'x0': 2,
            'y0': 2,
            'x1': 5,
            'y1': 2,
            'line': {
                'color': 'rgb(50, 171, 96)',
                'width': 4,
                'dash': 'dashdot',
            }
        }
    ]
}

fig = {
    'data': data,
    'layout': layout,
}

py.iplot(fig, filename='shapes-lines')

But I wonder if there is any ways to add legend for the horizontal lines.但我想知道是否有任何方法可以为水平线添加图例。

I think the only option at the moment is to plot it as a Scatter trace.我认为目前唯一的选择是将其绘制为 Scatter 跟踪。

For example this snippet of code例如这段代码

import plotly.graph_objects as pgo
fig = pgo.Figure()

fig.add_traces([
    pgo.Scatter(
        x=[2, 3.5, 6],
        y=[1, 1.5, 1],
        name='Yet Another Trace'
    ), 
    pgo.Scatter(
        x=[2,5],
        y=[2,2], 
        line={
            'color': 'rgb(50, 171, 96)',
            'width': 4,
            'dash': 'dashdot',
        }, name='Horizontal Line'
    )
])

fig.update_layout(**{
    'xaxis': {
        'range': [0, 7]
    },
    'yaxis': {
        'range': [0, 2.5]
    }
})

fig

generates this result:产生这个结果:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM