在Plotly中将线悬停在文本上 [英] Line hover text in Plotly
问题描述
我正在使用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.
推荐答案
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.
这是对我有用的代码
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.
这篇关于在Plotly中将线悬停在文本上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!