python - 绘制悬停数据和悬停文本

标签 python plotly data-visualization plotly-python

我的输入:

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()

我的输出: enter image description here .

如您所见,我在条形图中创建了一些自定义绘图。现在我试着做一些“闪光”,但有点困惑。我想要和期望:我尝试在弹出窗口(悬停文本)中隐藏任何 x=1variable=quality_value(即来自 x 和 y 轴的值) 然后离开 自定义名称中只有来自 hover_data 的标签,不像现在(hover_data_0label)

最佳答案

您可以通过以下设置使用 fig.update_traces(hovertemplate):

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

plotly 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()

关于python - 绘制悬停数据和悬停文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70737668/

相关文章:

python - 将每页选择器添加到 Django 管理 ListView

python - 使用 AWS CDK (python) 创建 Glue 作业失败

python - Plotly:如何在不更改数据源的情况下更改 go.pie 图表的图例?

python - Matplotlib 不显示不同语言(印地语)的字符和表情符号等其他字符

r - 在 R 中呈现线性回归模型的调节效应时如何反转对数变换?

python - 为什么线程不停止?

python - 如何在 Django 项目设置期间创建组和分配权限?

python - 将颜色映射到 plotly go.Pie 图表中的标签

r - 使用 rpart 生成桑基图的决策树

r - 图例中的符号和颜色分开