Skip to content
Advertisement

Add a number in textbox using add_annotations plotly python

How should I set up text in order to get “r-square: 0.90”?

Set up:

fig.add_annotation(dict(x=0.5,
                        y=0.85,
                        showarrow=False,
                        text= "r-square: %{a:.2f}",
                        textangle=0,
                        xanchor='left',
                        font=dict(size=20, color="black", family="Courier New, monospace"),
                                #opacity=0.8,
                                xref="paper",
                                yref="paper"))

Where:

a = px.get_trendline_results(fig).px_fit_results.iloc[0].rsquared
g = float("{0:.2f}".format(a)) # I also tried with this

but it is not working.

Advertisement

Answer

You can use an f-string instead. For example, here is what I get when I use the tips dataset:

import plotly.express as px

## use the tips dataset
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", trendline="ols")

a = px.get_trendline_results(fig).px_fit_results.iloc[0].rsquared
fig.add_annotation(dict(x=0.5,
                        y=0.85,
                        showarrow=False,
                        text= f"r-squared: {a:.2f}",
                        textangle=0,
                        xanchor='left',
                        font=dict(size=20, color="black", family="Courier New, monospace"),
                                xref="paper",
                                yref="paper"))
fig.show()

enter image description here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement