3

I am visualizing a UMAP 2D reduction of a Doc2Vec vector space as an interactive scatter plot with Plotly.

Each point corresponds to a document vector. Aside from the hovering behavior (which displays some information about the document), I want to be able to click on the points so that the URL of the document opens in a new window.

Here is my current code for the figure:

fig = go.Figure()

for cat in data.Categories.unique():
  if cat != 'OTHER':
    cat_data = data[data['Categories'] == cat]
    fig.add_trace(go.Scattergl(
        x=cat_data["Component 1"],
        y=cat_data["Component 2"],
        name=cat,
        mode="markers",
        opacity=0.8,
        marker=dict(size=5),
        text=['Label: %s<br>Title: %s'%(d,t) for d,t in cat_data.loc[:,['Labels', 'Document Titles']].values],
        hoverinfo="text"
        ))

fig.update_layout(
    title=title,
    font=dict(
        family="Lato",
        size=16,
        color="#000000"),
    hovermode='closest'
    )

fig.write_html("Plotly/2D_[NN-%s]_[MD-%s].html"%(n_neighbors, min_dist))

I have no idea where to start, reading through Plotly documentation didn't seem to help.

Many thanks in advance!

rpanai
  • 12,515
  • 2
  • 42
  • 64
Paul Miller
  • 493
  • 1
  • 5
  • 13

1 Answers1

3

Have you checked this answer or this forum post. Eventually you can play with click-events

Anyway if you look for a quick solution you can consider to add the link as annotation or hovertext as you can use html formatted code as text. I prefer the annotation/text scatter over hovertext as in the latter case it's a pain to correctly click.

import pandas as pd
import plotly.graph_objs as go

df = pd.DataFrame({"x":[0,1],
                  "y":[0,1],
                   "text":["<a href=\"https://plot.ly/\">name1</a>",
                           "<a href=\"https://google.com\">name2</a>"]})

fig =  go.Figure()
fig.add_trace(
    go.Scatter(x=df["x"],
               y=df["y"],
               mode="markers+text",
               # Just pick one of the two
               hovertext=df["text"],
               text=df["text"],
               textposition="top center",
               textfont_size=8))

fig.show()
rpanai
  • 12,515
  • 2
  • 42
  • 64
  • Thanks a lot, that might work but I already have some text in the hoverinfo (as shown in my example). How would I combine this with the annotation trick to get data point that (1) show some info when hovered on, and (2) and clickable to open URLs? – Paul Miller Apr 26 '20 at 07:58
  • If you can provide a [mcve](/help/mcve) ie provide a sample of your data I could better help. Anyway i'd consider having 2 columns on your dataframe one with the text you want to show and one with the url. After that you can make a third column which contains text plus hyperlink. – rpanai Apr 26 '20 at 12:24