WillacyMe
WillacyMe

Reputation: 582

Plotly: How to create custom hover Labels for Plotly 3D Scatter figures?

I'm using plotly to graph the similarities between movies based on their plot using PCA. Since this is just a visual representation I'm trying to produce, I don't really care about seeing the PCA values for each data point. I just want to see the title of the film, and maybe some other features like genre and rating. The x,y,z values are just making the graph look messy.

Below is the actual code used, although I don't have the movie_similarities function, it does just return a dataframe return pd.DataFrame({'pca_0':np.array([0,1,2,3]), 'pca_1':np.array([0,1,2,3]),'pca_2':np.array([0,1,2,3]),'Title':np.array(['Fight Club','Mission: Impossible','Harry Potter'])})

import plotly.graph_objects as go
import numpy as np
import plotly.offline as pyo
pyo.init_notebook_mode()


    df = pd.DataFrame({'pca_0':np.array([0,1,2,3]), 'pca_1':np.array([0,1,2,3]),'pca_2':np.array([0,1,2,3]),'Title':np.array(['Fight Club','Mission: Impossible','Harry Potter'])})`
    fig = go.Figure(data=[go.Scatter3d(
        x=df.pca_0, # ie [0, 1, 2, 3]
        y=df.pca_1, # ie [0, 1, 2, 3]
        z=df.pca_2, # ie [0, 1, 2, 3]
        hovertext = df.Title, # ie ['Fight Club','Mission: Impossible','Harry Potter']
        mode='markers',
        marker=dict(
            size=8,
            opacity=0.8
        )
    )])

    fig.show()

Upvotes: 2

Views: 3872

Answers (1)

vestland
vestland

Reputation: 61074

Focusing on...

I don't really care about seeing the PCA values for each data point. I just want to see the title of the film

... the right combination of hovertemplate='<b>%{text}</b>' and text should do the trick`:

enter image description here

Complete code with data sample:

import plotly.graph_objects as go
import numpy as np
import plotly.offline as pyo
import pandas as pd
pyo.init_notebook_mode()


df = pd.DataFrame({'pca_0':np.array([4,1,2,3]),
                   'pca_1':np.array([9,11,12,13]),
                   'pca_2':np.array([0,5,1,8]),
                   'Title':np.array(['Fight Club','Mission: Impossible','Harry Potter', 'Star Wars'])})
fig = go.Figure(data=[go.Scatter3d(
    x=df.pca_0, # ie [0, 1, 2, 3]
    y=df.pca_1, # ie [0, 1, 2, 3]
    z=df.pca_2, # ie [0, 1, 2, 3]
    hovertemplate='<b>%{text}</b><extra></extra>',
    text = [title for title in df.Title],
    mode='markers',
    marker=dict(
        size=8,
        opacity=0.8
    )
)])

fig.show()

Upvotes: 4

Related Questions