Leolime
Leolime

Reputation: 317

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?

Upvotes: 10

Views: 31761

Answers (2)

abhishek singh
abhishek singh

Reputation: 181

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

Upvotes: 18

sentence
sentence

Reputation: 8903

To change the background color you need specify it by plot_bgcolor='rgba(0,0,0,0)',, while to move the legend inside the plot, on the left, you need to explicitly define the position:

import plotly.graph_objects as go

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

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

data = [trace0, trace1]
layout = go.Layout(
        plot_bgcolor='rgba(0,0,0,0)',
    legend=dict(
        x=0,
        y=0.7,
        traceorder='normal',
        font=dict(
            size=12,),
    ),
    annotations=[
        dict(
            x=0,
            y=0.75,
            xref='paper',
            yref='paper',
            text='Trend',
            showarrow=False
        )
    ]
)
fig = go.Figure(data = data,
                layout = layout)

fig.update_xaxes(showgrid=True, gridwidth=1, gridcolor='LightGray')
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='LightGray')

fig.show()

and you get:

enter image description here

Upvotes: 8

Related Questions