william_grisaitis
william_grisaitis

Reputation: 5911

Adding text labels to a plotly scatter plot for a subset of points

I have a plotly.express.scatter plot with thousands of points. I'd like to add text labels, but only for outliers (eg, far away from a trendline).

How do I do this with plotly?

I'm guessing I need to make a list of points I want labeled and then pass this somehow to plotly (update_layout?). I'm interested in a good way to do this.

Any help appreciated.

Upvotes: 4

Views: 4569

Answers (1)

Derek O
Derek O

Reputation: 19545

You have the right idea: you'll want to have the coordinates of your outliers, and use Plotly's text annotations to add text labels to these points. I am not sure how you want to determine outliers, but the following is an example using the tips dataset.

import pandas as pd
from sklearn import linear_model
import plotly.express as px

df = px.data.tips()

## use linear model to determine outliers by residual
X = df["total_bill"].values.reshape(-1, 1)
y = df["tip"].values

regr = linear_model.LinearRegression()
regr.fit(X, y)

df["predicted_tip"] = regr.predict(X)
df["residual"] = df["tip"] - df["predicted_tip"]
residual_mean, residual_std = df["residual"].mean(), df["residual"].std()
df["residual_normalized"] = (((df["tip"] - df["predicted_tip"]) - residual_mean) / residual_std).abs()

## determine outliers using whatever method you like
outliers = df.loc[df["residual_normalized"] > 3.0, ["total_bill","tip"]]

fig = px.scatter(df, x="total_bill", y="tip", trendline="ols", trendline_color_override="red")

## add text to outliers using their (x,y) coordinates:
for x,y in outliers.itertuples(index=False):
    fig.add_annotation(
        x=x, y=y,
        text="outlier",
        showarrow=False,
        yshift=10
    )
fig.show()

enter image description here

Upvotes: 4

Related Questions