Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position legends inside a plot in Plotly

I have got this code from Plotly page. I need to make the background transparent and the axis highlighted. And also the legends positioned inside the plot.

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[1, 2, 3, 4, 5],
    name="Increasing"
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[5, 4, 3, 2, 1],
    name="Decreasing"
))

fig.update_layout(legend_title='<b> Trend </b>')
fig.show()

The code above shows the output below:

enter image description here

My expected output:

enter image description here

Hoow can i convert the first image to get the features of the second image?

like image 724
Leolime Avatar asked Feb 08 '20 03:02

Leolime


People also ask

How do I change my legend location on Plotly?

To position the legend we use the update_layout function with legend set to a dictionary that describes the attributes of a legend. anchor keys set position and x and y accommodate the margin with respect to axis.

How do you show legends in Plotly?

Grouped Legend Plotly legends are interactive. Click on the legend entries to hide and show traces. The legendgroup key groups legend entries so that clicking on one legend entry will hide or show all of the traces in that group.

How do you make a legend horizontal in Plotly?

orientation attribute can be set to "h" for a horizontal legend. Here we also position it above the plotting area.

How do you hide legends in Plotly?

In this example, we are hiding legend in Plotly with the help of method fig. update(layout_showlegend=False), by passing the showlegend parameter as False.


1 Answers

import plotly.graph_objects as go

fig = go.Figure()

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[1, 2, 3, 4, 5],
))

fig.add_trace(go.Scatter(
    x=[1, 2, 3, 4, 5],
    y=[5, 4, 3, 2, 1],
))

fig.update_layout(
    legend=dict(
        x=0,
        y=.5,
        traceorder="normal",
        font=dict(
            family="sans-serif",
            size=12,
            color="black"
        ),
    )
)
fig.show()

change the value of x and y between 0 to 1

output

like image 82
abhishek singh Avatar answered Nov 06 '22 19:11

abhishek singh