使用 add_annotations plotly python 在文本框中添加数字

Add a number in textbox using add_annotations plotly python

我应该如何设置 text 以获得 "r-square: 0.90"?

设置:

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"))

其中:

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

但它不起作用。

您可以改用 f-string。例如,这是我使用提示数据集时得到的:

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()