Plotly legend is not rendered

Question:

I am drawing a plot that has two lines with the following code. I have enabled legend but it is not rendered. What should be the reason for this?

figure = go.Figure(px.line(x=[1,2,3],
                           y=[2,4,6],
                           markers=True,
                           ))
figure.add_hline(y=3, line_width=1.5, line_dash='dash',
                 line_color='green', name='line label')

figure.update_traces(
    marker_size=5,
    marker_line=dict(width=2, color='red'))

figure.update_layout(
    title='My title',
    yaxis_title='Y title',
    xaxis_title='X title',
    showlegend=True
)


figure.add_hline(y=24, line_width=1.5, line_dash='dash',
                 line_color='green', name='trace 0')
Asked By: Malintha

||

Answers:

Try

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Scatter(x=[1, 2, 3], y=[2, 4, 6], mode='markers+lines'))
fig.update_traces(marker_size=12, marker_line=dict(width=2, color='red'))
fig.update_layout(title='My title', yaxis_title='Y Title', xaxis_title='X Title', showlegend=True)
fig.add_hline(y=24, line=dict(width=2, color='green', dash='dash'), annotation_text='trace 0')
fig.show()

enter image description here

Answered By: Baron Legendre
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.