Plotly,更改悬停文本

3

我想要修改 Plotly 中的悬停文本。 例如,有一个

import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    '<b>%{text}</b>',
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))

fig.add_trace(go.Scatter(
    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}<extra></extra>',
    showlegend = False))

fig.update_layout(
    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")

fig.show()

enter image description here

你能看到蓝色部分,上面写着“trace 0”。它是从哪里来的? 如果你在红色曲线上悬停,你会注意到类似的东西没有出现。

我想要重现这个,所以我想要了解它的来源。

1个回答

2
你可以通过删除/添加<extra></extra>标签来启用/禁用每组点的trace0,trace1,...文本。有关悬停文本自定义的文档可以在这里找到。
要使trace1出现在第二组点上,请删除<extra></extra>标记。
import plotly.graph_objects as go

fig = go.Figure(go.Scatter(
    x = [1,2,3,4,5],
    y = [2.02825,1.63728,6.83839,4.8485,4.73463],
    hovertemplate =
    '<i>Price</i>: $%{y:.2f}'+
    '<br><b>X</b>: %{x}<br>'+
    '<b>%{text}</b>',
    text = ['Custom text {}'.format(i + 1) for i in range(5)],
    showlegend = False))

## Remove the extra tag
fig.add_trace(go.Scatter(
    x = [1,2,3,4,5],
    y = [3.02825,2.63728,4.83839,3.8485,1.73463],
    hovertemplate = 'Price: %{y:$.2f}',
    showlegend = False))

fig.update_layout(
    hoverlabel_align = 'right',
    title = "Set hover text with hovertemplate")

fig.show()

enter image description here


实际上我不想禁用它,相反,我想让它出现在任何地方(比如红色曲线中)。默认情况下它会出现,但当我修改悬停文本时它就消失了。我将根据您提供的信息进行一些实验,看看效果如何! - KansaiRobot
更新了——希望这能帮到你。 - Derek O

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接