Plotly:如何仅将垂直线和水平线(十字线)显示为悬停信息?

2024-09-07 16:40:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用plotly dash中的两个子图绘制一张图表。我的整个图表如下所示:

import pandas as pd
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from plotly.subplots import make_subplots
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]
fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)

fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'],
                             increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)

fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)

fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"},
                  legend=dict(y=1, x=0),
                  font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified',
                  margin=dict(b=20, t=0, l=0, r=40))

fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
                 showspikes=True, spikemode='across', spikesnap='data', showline=False, spikedash='solid')

fig.update_yaxes(showgrid=False, zeroline=False)
fig.update_traces(xaxis='x', hoverinfo='none')

app = dash.Dash(__name__)

app.layout = html.Div(children=[
    html.Div(dcc.Graph(id='chart', figure=fig, config={'displayModeBar': False}))])

if __name__ == '__main__':
    app.run_server(debug=True, dev_tools_ui=False, dev_tools_props_check=False)

我需要的是一个在交易图表中常见的所谓的十字线。基本上,它由两条线组成,这两条线连接到x轴和y轴,并随光标移动。这是tradingview.com图表中的屏幕截图: enter image description here

但是,在我的图表中,当光标位于烛台上时,会出现一个小图标: enter image description here

到目前为止,我发现当光标位于散点图上时,图标消失,工作正常。我想那是因为我在散点图中设置了hovertemplate=[]。我不能在烛台图中这样做,因为它没有这样的参数。此外,此图标仅在我设置hovermode='x unified'时显示。如果我将其设置为x,则小图标不会出现。但我需要它完全像我展示的tradingview.com示例一样。 有没有办法复制这种交叉线

更新1:

我试过了。但问题是,当光标不在烛台上时,十字线就不对了。我拍了两张截图:第一张来自tradingview.com图表,第二张来自我的代码,其中hoverdistance设置为0。enter image description here{a4} 可以看出,当光标不在烛台上时,在第一个屏幕截图中十字线仍然正确。然而,在第二个屏幕截图中,它只是工作不正常。仅当光标位于烛台上时,此功能才起作用。 我只想复制tradingview.com十字线。不多也不少

更新2:

我认为答案可能在这些问题上。我目前正在做这件事。请分享您对此更新的评论


Tags: nameimportcomfalsedfhtmlas图表
2条回答

如果您设置了hovermode='x',那么您可以像这样格式化style of the spike line

fig.update_xaxes(spikecolor="grey",spikethickness=1)

更新: spikesnap='cursor'会让你离得更近,但不完全适用于烛台

fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
                 showspikes=True, spikemode='across', spikesnap='cursor', showline=False,
                 spikecolor="grey",spikethickness=1, spikedash='solid')
fig.update_yaxes(showspikes=True, spikedash='solid',spikemode='across', 
                spikecolor="grey",spikesnap="cursor",spikethickness=1)
fig.update_layout(spikedistance=1000,hoverdistance=1000)

这应该做到:

fig.update_layout(hoverdistance=0)

以及为xax和yax设置spikesnap='cursor'

这些小小的调整将保持十字线的完整性,并删除困扰您的小图标

the docs

绘图:

enter image description here

hoverdistance

Sets the default distance (in pixels) to look for data to add hover labels (-1 means no cutoff, 0 means no looking for data). This is only a real distance for hovering on point-like objects, like scatter points. For area-like objects (bars, scatter fills, etc) hovering is on inside the area and off outside, but these objects will not supersede hover on point-like objects in case of conflict.

完整代码:(但不带破折号元素)

import pandas as pd
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').iloc[:60]
fig = make_subplots(rows=2, cols=1, row_heights=[0.8, 0.2], vertical_spacing=0)

fig.add_trace(go.Candlestick(open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'],
                             increasing_line_color='#0384fc', decreasing_line_color='#e8482c', name='AAPL'), row=1, col=1)

fig.add_trace(go.Scatter(y=np.random.randint(20, 40, len(df)), marker_color='#fae823', name='VO', hovertemplate=[]), row=2, col=1)

fig.update_layout({'plot_bgcolor': "#21201f", 'paper_bgcolor': "#21201f", 'legend_orientation': "h"},
                  legend=dict(y=1, x=0),
                  font=dict(color='#dedddc'), dragmode='pan', hovermode='x unified',
                  margin=dict(b=20, t=0, l=0, r=40))

fig.update_yaxes(showgrid=False, zeroline=False, showticklabels=False,
                 showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')

fig.update_xaxes(showgrid=False, zeroline=False, rangeslider_visible=False, showticklabels=False,
                 showspikes=True, spikemode='across', spikesnap='cursor', showline=False, spikedash='solid')

fig.update_layout(hoverdistance=0)

fig.update_traces(xaxis='x', hoverinfo='none')
fig.show()

相关问题 更多 >