plotly Scatter 自定义数据仅 NaN

问题描述 投票:0回答:2

我想在将鼠标悬停在 go.Scatter 创建的曲线上时显示附加数据。使用下面的脚本,弹出窗口中会显示正确的 x 和 y 值,但 x^2 和 cos 始终显示为 NaN。我将非常感谢任何帮助。

import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objects as go
import numpy as np

x = np.mgrid[0.0:10.0:100j]
y = np.sin(x)

fig = go.Figure()
fig.add_trace(go.Scatter(x = x, y = y, line_width = 4,
                        customdata = [x**2, np.cos(x)],
                        hovertemplate = "<br>".join([
                            "x = %{x:,.1f}",
                            "y = %{y:,.1f}",
                            "x^2 = %{customdata[0]:,.1f}",
                            "cos = %{customdata[1]:,.1f}"
                        ])
                    ))

app = dash.Dash()
app.layout = html.Div([dcc.Graph(figure=fig)])
app.run_server()
hover plotly scatter dataset
2个回答
2
投票
import plotly.graph_objects as go
import numpy as np

x = np.mgrid[0.0:10.0:100j]
y = np.sin(x)

custom_data = np.stack((x**2, np.cos(x)), axis=-1)

fig = go.Figure()
fig.add_trace(go.Scatter(x = x, y = y, line_width = 4))
fig.update_traces(customdata=custom_data,

hovertemplate ="x: %{x}<br>"+\
               "y: %{y}<br>"+\
               "x**2: %{customdata[0]: .1f}<br>"+\
               "cos: %{customdata[1]: .1f}")
fig.show()


0
投票

对于使用静态标签或其他数据点时遇到此问题的其他人:

customdata 数组长度必须与输入数据集的长度匹配。

例如变量 wd、dc 和数据帧 df :

customdata = np.array([[int(wd),int(dc)] for x in np.arange(len(df))])
© www.soinside.com 2019 - 2024. All rights reserved.