I can successfully create a scatter plot based on a simple DataFrame that’s comprised of just 2 columns – Date and Value.
I can add some horizontal lines to highlight the start, lowest and highest values.
The scatter plot includes a trendline.
I know how to extract the r2 value but what I can’t figure out is how to show the r2 on the plot. I don’t really care where it goes although ideally it would be on the trendline.
Here’s what I have.
import plotly.express as px
from finance import get_df
if __name__ == "__main__":
df = get_df()
tl = px.scatter(df, x="Date", y="Value", trendline="ols")
value = df["Value"]
tl.add_hline(
y=value.iloc[0],
annotation_text="Start value",
annotation_position="bottom left",
)
tl.add_hline(
y=value.min(),
line_color="red",
annotation_text="Lowest value",
annotation_position="bottom left",
)
tl.add_hline(
y=value.max(),
line_color="green",
annotation_text="Highest value",
annotation_position="bottom left",
)
tl.update_traces(
hovertemplate="<i>Value</i>: £%{y:,.2f}",
marker={"size": 8, "line": {"width": 1}},
selector={"mode": "markers"},
)
# Here's the r-squared value
r2 = px.get_trendline_results(tl).px_fit_results.iloc[0].rsquared
tl.show()