Plotly 鼠标悬停数据和悬停文本

3

我的输入:

df=(pd.DataFrame({'label_color':['white','white','cyan','cyan','cyan','cyan','white','white'],
                  'label_quality':['white','white','red','green','green','red','white','white'],
'label':['foo','foo','foo','foo','foo','foo','foo','foo']}))

我的代码:

df['color_value'] = 1
df['quality_value'] = 1

fig = px.bar(df, y=['color_value','quality_value'],
             x=[1]*len(df),
             orientation='h',
             barmode='group',
             template='plotly_white', hover_data=[df.index.values,df.label])

fig.data[0]['marker']['color'] = df['label_color'].tolist()
fig.data[1]['marker']['color'] = df['label_quality'].tolist()
fig.update_traces(marker_line_color='rgb(8,48,107)')
fig.update_layout(showlegend=False, yaxis_title='foo', xaxis_title='')
fig.show()

我的输出结果:在这里输入图片描述

正如您所见,我在柱状图中创建了一些自定义绘图。现在我想要添加一些“闪光点”,但有点困惑。我希望:当鼠标悬停在数据上时,在弹出窗口中隐藏任何 x=1, variable=quality_value (即来自 x 和 y 轴的值),只显示 hover_data 中自定义名称的标签(而不是像现在这样的 hover_data_0label)。

1个回答

3

您可以使用以下设置的fig.update_traces(hovertemplate)

fig.update_traces(hovertemplate = 'hover_data_0=%{customdata[0]}<br>label=%{customdata[1]}<extra></extra>')

情节1:

enter image description here

完整代码:

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

df=(pd.DataFrame({'label_color':['white','white','cyan','cyan','cyan','cyan','white','white'],
                  'label_quality':['white','white','red','green','green','red','white','white'],
'label':['foo','foo','foo','foo','foo','foo','foo','foo']}))

df['color_value'] = 1
df['quality_value'] = 1

fig = px.bar(df, y=['color_value','quality_value'],
             x=[1]*len(df),
             orientation='h',
             barmode='group',
             template='plotly_white', hover_data=[df.index.values,df.label])

fig.data[0]['marker']['color'] = df['label_color'].tolist()
fig.data[1]['marker']['color'] = df['label_quality'].tolist()
fig.update_traces(marker_line_color='rgb(8,48,107)')
fig.update_layout(showlegend=False, yaxis_title='foo', xaxis_title='')
fig.update_traces(hovertemplate = 'hover_data_0=%{customdata[0]}<br>label=%{customdata[1]}<extra></extra>')
fig.show()

谢谢回答,但我遇到了一个错误:“完整图像生成需要kaleido包”,我使用的是Anaconda作为Python环境。不过,即使没有f=fig.full_figure_for_development(warn=False)这一行,它仍然能够正常工作。 - TeoK
@TeoK 你也不需要它。这只是一种检查 Plotly 图形结构的方法。感谢您接受我的答案。 - vestland

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