0

I draw a figure using plotly (python) as shown in below. enter image description here

Now my aim is to show all points in same color but add different text for each colored part from this figure. For example, for the blue part I want to add the text AAA and for the red part BBB. How to do that in plotly?

1 Answer 1

1
  • I have simulated data with features that will generate a graph similar to one you have shown
  • there are three ways to add labels
    1. labels against traces in legend
    2. as additional scatter plots with mode="text"
    3. as annotations on the figure

All three of these are demonstrated below. It does assume you have a working knowledge of pandas

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

df = pd.DataFrame({"AAA":np.concatenate([np.random.uniform(1,5,20), np.full(20,np.nan)]), 
              "BBB":np.concatenate([np.full(20,np.nan), np.random.uniform(1,5,20), ])})

# create two traces, where traces are in legend to label AAA & BBB
fig = px.scatter(df, x=df.index, y=["AAA","BBB"]).update_traces(mode="lines+markers")

# additionally create text trace, that are last AAA & BBB
lastAAA = df.loc[~df["AAA"].isna()].iloc[-1]
lastBBB = df.loc[~df["BBB"].isna()].iloc[-1]
fig.add_trace(go.Scatter(x=[lastAAA.name], y=[lastAAA["AAA"]], text="AAA", mode="text", showlegend=False))
fig.add_trace(go.Scatter(x=[lastBBB.name], y=[lastBBB["BBB"]], text="BBB", mode="text", showlegend=False))

# additionally add annotations
fig.add_annotation(x=lastAAA.name, y=lastAAA["AAA"], text="AAA")
fig.add_annotation(x=lastBBB.name, y=lastBBB["BBB"], text="BBB")

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.