user3447653
user3447653

Reputation: 4148

Highlight a section of the plot in a plotly graph

I plot the below dataframe using plotly. I am trying to highlight the area (using a circle or rectangle) if the value of dist1 is < 0.5 and value of dist2 is > 15. Not sure is there a way to achieve this using plotly.

 import plotly.express as px
 import matplotlib.pyplot as plt

 for i in range(len(values)):
    df_results = pd.DataFrame.from_records(values[i][1])
    df_results.columns = ['value','dist1','dist2']
    plt.figure(figsize=[15,7])
    fig = px.scatter(df_results, x="dist1", y="dist2")
    fig.show()

Sample dataframe:

 value   dist1    dist2
 A-0     0.4      16.0
 A-1     0.3      18.0
 A-2     0.9      5.0
 A-4     1.0      2.0
 A-5     0.2      18.0

After plotting the above dataframe, would like to highlight the region where dist1 is less than 0.5 and dist2 is greater than 15.

Any suggestions would be appreciated.

Upvotes: 1

Views: 3260

Answers (1)

Rob Raymond
Rob Raymond

Reputation: 31146

  • the simplest way is to color points in scatter. Using a straight forward mask for this
  • to shade an area, you can create a shape https://plotly.com/python/shapes/
    • have created a dataframe to calculate the x0, y0, x1, y1 coordinates
    • not sure if you have multiple areas for this, hence have created shapes for any set of contiguous areas
import io
import pandas as pd
import plotly.express as px

df_results = pd.read_csv(
    io.StringIO(
        """ value   dist1    dist2
 A-0     0.4      16.0
 A-1     0.3      18.0
 A-2     0.9      5.0
 A-4     1.0      2.0
 A-5     0.2      18.0"""
    ),
    sep="\s+",
)


# order is important for finding contiguous area
df_results = df_results.sort_values(["dist1", "dist2"]).reset_index(drop=True)

mask = df_results["dist1"].lt(0.5) & df_results["dist2"].gt(15)
fig = px.scatter(df_results, x="dist1", y="dist2", color=mask)

for r in (
    df_results.loc[mask]
    .reset_index() # for finding contigouous rows
    .assign(area=lambda d: ((d["index"] - d["index"].shift()) != 1).cumsum())
    .groupby("area")
    .agg(
        minx=("dist1", "min"),
        maxx=("dist1", "max"),
        miny=("dist2", "min"),
        maxy=("dist2", "max"),
    )
    .iterrows()
):
    fig.add_shape(
        type="rect",
        x0=r[1]["minx"],
        x1=r[1]["maxx"],
        y0=r[1]["miny"],
        y1=r[1]["maxy"],
        fillcolor="green",
        opacity=0.2,
    )


fig

enter image description here

Upvotes: 1

Related Questions