Elena Greg
Elena Greg

Reputation: 1165

How to add text to plotly?

I would like to add text not corresponding to a point. I tried the following script:

import pandas as pd
import plotly.express as px


## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')

fig.add_annotation(text="Absolutely-positioned annotation",
                  xref="paper", yref="paper",
                  x=1.5, y=5.2, showarrow=False)

fig.show()

Edit after advice:

How to combine the command with go.Layout?

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')

fig.add_annotation(text="Absolutely-positioned annotation",
                  x=2.5, y=4.5, showarrow=False)

layout = go.Layout(
    template = "plotly_white",
)

fig.layout = layout

fig.show()

Upvotes: 1

Views: 682

Answers (1)

vestland
vestland

Reputation: 61104

You're assigning xref="paper", yref="paper". This implies that your values will have to be in the interval [0, 1] to appear on your plot:

enter image description here

Complete code:

import pandas as pd
import plotly.express as px


## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})


fig = px.scatter(df1, x='A', y='B')

# fig.add_annotation(text="Absolutely-positioned annotation",
#                   xref="x", yref="y",
#                   x=1.5, y=5.2, showarrow=False)

fig.add_annotation(text="Absolutely-positioned annotation",
                  xref="paper", yref="paper",
                  x=0.4, y=0.4, showarrow=False)

fig.show()

Upvotes: 1

Related Questions