如何移除Plotly Express自定义悬浮卡片右侧的颜色标签
问题原因
当你在px.bar中指定了color参数时,Plotly默认会将颜色维度的对应值显示在悬浮卡片的右侧额外区块(也就是内置的<extra>模板区块),即便你自定义了hovertemplate,这个区块默认还是会保留内容。
解决方法
只需要在自定义的hovertemplate末尾追加<extra></extra>,将额外区块设为空即可,修改后的代码如下:
import pandas as pd import plotly.express as px df = pd.DataFrame(dict(x=["a"], y=[1], color=["blue"], hover=["a=1"])) fig = px.bar(df, "x", "y", "color", custom_data=["hover"]) # 追加<extra></extra>清空右侧额外信息 fig.update_traces(hovertemplate="%{customdata[0]}<extra></extra>")
如果有自定义右侧区块内容的需求,也可以直接往<extra>标签中间填入你需要的模板变量,比如要显示y值就写成<extra>y值:%{y}</extra>即可。
内容的提问来源于stack exchange,提问作者Max Ghenis
相关产品推荐
相关产品推荐

