悬停数据未显示在绘图图中

Hover data does not show up in plotly graph

我想要一个雷达图,该图已填充并具有悬停信息。我只得到其中一个工作。这是一个例子:

假设我们有未透视的数据:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'sample':['sample_1','sample_2','sample_3','sample_1','sample_2','sample_3','sample_1','sample_2','sample_3'],
                  'KPI':['KPI_1','KPI_1','KPI_1','KPI_2','KPI_2','KPI_2','KPI_3','KPI_3','KPI_3'],
                  'value':[1,2,1,1,1,2,2,1,1],
                  'sample_info':['info_1','info_1','info_1','info_2','info_2','info_2','info_3','info_3','info_3']})
df
    sample      KPI     value   sample_info
0   sample_1    KPI_1   1   info_1
1   sample_2    KPI_1   2   info_1
2   sample_3    KPI_1   1   info_1
3   sample_1    KPI_2   1   info_2
4   sample_2    KPI_2   1   info_2
5   sample_3    KPI_2   2   info_2
6   sample_1    KPI_3   2   info_3
7   sample_2    KPI_3   1   info_3
8   sample_3    KPI_3   1   info_3

我想要一个悬停在 sample_info 上的雷达图,像这样:

fig = px.line_polar(df, r='value', theta='KPI', color='sample',line_close = True,
                   hover_data = ['sample_info'])
fig.show()

output

效果很好。现在我想填充图形:

fig = px.line_polar(df, r='value', theta='KPI', color='sample',line_close = True,
                   hover_data = ['sample_info'])
fig.update_traces(fill='toself')
fig.show()

现在,悬停信息以某种方式被覆盖了。我用 custom_data 和一个 hovertemplate 试了一下:

fig = px.line_polar(df, r='value', theta='KPI', color='sample',line_close = True,
                   custom_data = ['sample_info'])
fig.update_traces(fill='toself',hovertemplate="'sample_info: %{customdata[0]}'")
fig.show()

但没有成功。我错过了什么?提前致谢!

您可以使用:

fig.for_each_trace(lambda t: t.update(hoveron='points'))

并得到:

完整代码:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'sample':['sample_1','sample_2','sample_3','sample_1','sample_2','sample_3','sample_1','sample_2','sample_3'],
                  'KPI':['KPI_1','KPI_1','KPI_1','KPI_2','KPI_2','KPI_2','KPI_3','KPI_3','KPI_3'],
                  'value':[1,2,1,1,1,2,2,1,1],
                  'sample_info':['info_1','info_1','info_1','info_2','info_2','info_2','info_3','info_3','info_3']})

fig = px.line_polar(df, r='value', theta='KPI', color='sample',line_close = True,
                   hover_data = ['sample_info'])
fig.update_traces(fill='toself')

fig.for_each_trace(lambda t: t.update(hoveron='points'))

fig.show()