Plotly 中的行悬停文本文本、Plotly

2023-09-06 14:29:16 作者:越努力越幸运

我正在使用 Plotly 绘制一个类似于 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.

推荐答案

一个快速的解决方案/hack 是遵循 艾蒂安的想法.这个想法是在每一行上插入一个透明节点并用悬停文本标签对其进行注释.

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']))

然后只绘制所有轨迹,即 [*trace3_list, middle_node_trace].

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.