pentavol
pentavol

Reputation: 119

Custom hover for scatter plot by color

I am using plotly and I try to make a scatterplot colored by a variable, while using another variable to indicate what text should be showed when covering the mouse over a specific point. Look what I tried:

df = pd.DataFrame({
    'class': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'], 
    'coord_x': [4,5,6,3,1,-1,9,0,3.5,2], 
    'coord_y': [11,32,48,22,12,29,32,54,19,21],
    'description':['some description for A', 'something else for A', 'other description for A', 'AAA', 'aaa', 'bbb', 'bbb', 'description for C', 'cccc', 'cc']
})

fig = px.scatter(df, x="coord_x", y="coord_y", color="class")
fig.update_traces(hovertemplate="Hover_text: %{text}",
        text=[d for d in df.description.values.tolist()])

fig.show()

The code seem to work, but it only the hover works "A" points, even though "B" and "C" don't have the same description in my pandas DataFrame. How should I solve this problem?

Upvotes: 2

Views: 1229

Answers (2)

Rob Raymond
Rob Raymond

Reputation: 31146

Have used graph objects rather than plotly express

  • main technique is to transform class variable to be a number
  • used index from array of unique values
import plotly.graph_objects as go

df = pd.DataFrame({
    'class': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'], 
    'coord_x': [4,5,6,3,1,-1,9,0,3.5,2], 
    'coord_y': [11,32,48,22,12,29,32,54,19,21],
    'description':['some description for A', 'something else for A', 'other description for A', 'AAA', 'aaa', 'bbb', 'bbb', 'description for C', 'cccc', 'cc']
})

# color needs to be a number, use index of unique values
go.Figure(data=go.Scatter(x=df.coord_x, y=df.coord_y, hoverinfo="text", text=df.description, mode="markers", 
                          marker={"color":df["class"].apply(lambda v: np.where(v==df["class"].unique())[0][0])}))

Upvotes: 1

Celius Stingher
Celius Stingher

Reputation: 18367

I believe you could add the argument hover_name in the function to make it show for each point:

fig = px.scatter(df, x="coord_x", y="coord_y", color="class",hover_name='description')

For example:

enter image description here

Upvotes: 1

Related Questions