Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line hover text in Plotly

Tags:

python

plotly

I am plotting a graph with Plotly similar to the example on the Plotly website.
Along with the hover text on the graph nodes, I want to have a hover text on the edges as well.

I tried to achieve this by modifying the trace object for edges by adding a 'name' field, but this didn't work and was putting the 'name' on the nodes.

trace3=Scatter(
    x=Xed,
    y=Yed,
    name="my_hover_text",
    mode='lines',
    line=Line(color='rgb(210,210,210)', width=1),
    hoverinfo='name'
)

Using the 'text' field instead of the 'name' field, gives the very same result.

I have also tried to have a separate trace for each edge, which should solve the confusion about where to put the name on the line, but this lead me nowhere.
As a bottom line, I need a way to put a (hover) label/text on a line connecting two points.

like image 613
gevra Avatar asked Sep 04 '17 13:09

gevra


People also ask

What is hover name in Plotly?

Hover Labels is the most depectively-power feature for interactive visualization in plotly, for user it is the ability to reveal more information about the data points by moving the cursor (mouse) over the point and having a hover label appear.

How do you show text in Plotly?

To show an arbitrary text in your chart you can use texttemplate, which is a template string used for rendering the information, and will override textinfo. This template string can include variables in %{variable} format, numbers in d3-format's syntax, and date in d3-time-format's syntax.


1 Answers

One quick solution/hack is to follow etienne's idea from the community forum page that Maximilian mentioned in the comment.
The idea is to insert a transparent node on each line and annotate it with a hover text label.

here is a code that worked for me

trace3_list = []
middle_node_trace = go.Scatter(
    x=[],
    y=[],
    text=[],
    mode='markers',
    hoverinfo='text',
    marker=go.Marker(
        opacity=0
    )
)
for edge in G.edges(data=True):
    trace3=Scatter(
        x=[],
        y=[],
        mode='lines',
        line=Line(color='rgb(210,210,210)', width=edge[2]['weight']),
        hoverinfo='none'
    )
    x0, y0 = G.node[edge[0]]['pos']
    x1, y1 = G.node[edge[1]]['pos']
    trace3['x'] += [x0, x1, None]
    trace3['y'] += [y0, y1, None]
    trace3_list.append(trace3)

    middle_node_trace['x'].append((x0+x1)/2)
    middle_node_trace['y'].append((y0+y1)/2)
    middle_node_trace['text'].append(str(edge[2]['weight']))

Then just plot all the traces, i.e. [*trace3_list, middle_node_trace].

BONUS: having a separate trace for each edge allows to set different widths, e.g. proportional to the edge weight.

like image 147
gevra Avatar answered Sep 25 '22 11:09

gevra