5
votes

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.

1
That's not currently not possible: community.plot.ly/t/…Maximilian Peters
thanks @MaximilianPeters ! I made it happen following etienne's idea of putting a transparent node on the line and annotating it with a hover text. I'll post some code soongevra

1 Answers

6
votes

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.