Reputation: 4148
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
Reputation: 31146
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
Upvotes: 1