如何在Plotly中禁用悬停时出现的黑色坐标线?
禁用Plotly悬停黑色坐标线并保留股票代码文本
你不需要关闭hovermode,悬停时的黑色坐标线是Plotly的spike线,可以单独禁用它,同时保留hover提示框里的股票代码。
实现方法
1. 单个轨迹(trace)禁用spike线
在添加股票数据的Scatter轨迹时,设置spikedash='none',同时通过hovertemplate指定hover显示的内容(包含股票代码):
import plotly.graph_objects as go # 示例数据 stock_codes = ["AAPL", "MSFT", "GOOGL"] dates = ["2024-01-01", "2024-01-02", "2024-01-03", "2024-01-04"] prices = [ [175, 178, 176, 180], [380, 385, 382, 388], [140, 142, 141, 145] ] fig = go.Figure() for code, price in zip(stock_codes, prices): fig.add_trace(go.Scatter( x=dates, y=price, name=code, # 自定义hover显示,确保股票代码可见 hovertemplate=f"股票代码: {code}<br>价格: %{{y}}<br>日期: %{{x}}<extra></extra>", spikedash='none' # 禁用该轨迹的spike线 )) # 保持hovermode开启,按需选择模式(x unified/closest等) fig.update_layout(hovermode='x unified') fig.show()
2. 全局禁用所有spike线
如果所有轨迹都不需要spike线,可以直接在坐标轴配置中全局设置:
fig.update_layout( hovermode='x unified', xaxis=dict(spikedash='none'), yaxis=dict(spikedash='none') )
关键参数说明
spikedash='none':将spike线的样式设为无,彻底隐藏黑色坐标线,不会影响hover提示框的显示。hovertemplate:自定义hover提示内容,<extra></extra>用来隐藏默认的轨迹名称(如果不需要的话),确保股票代码是核心显示内容。hovermode:必须保持开启状态(比如'x unified'会在同一x轴位置显示所有股票的hover信息,'closest'只显示最近的轨迹),这样才能触发hover提示框。
内容的提问来源于stack exchange,提问作者rudinable
相关产品推荐
相关产品推荐

