简体   繁体   English

Plotly:如何仅将垂直和水平线(十字准线)显示为 hoverinfo?

[英]Plotly: How to only show vertical and horizontal line (crosshair) as hoverinfo?

I want to plot a chart with two subplots in plotly dash.我想 plot 一个图表,在 plotly dash 中有两个子图。 My entire chart looks like this:我的整个图表如下所示:

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)

What I need is a so called crosshair that is common in trading charts.我需要的是交易图表中常见的所谓十字准线。 Basically it consists of two lines that are connected to x and y axes and moves with cursor.基本上它由连接到 x 轴和 y 轴并随 cursor 移动的两条线组成。 This is a screenshot from tradingview.com charts:这是来自 tradingview.com 图表的截图: 在此处输入图像描述

However in my chart there is a little icon that appears when the cursor is on candlesticks:然而,在我的图表中,当 cursor 位于烛台上时,会出现一个小图标: 在此处输入图像描述

What I have found out so far is that when the cursor is on the scatter plot, the icon disappears and it works fine.到目前为止我发现的是,当 cursor 在散布 plot 上时,图标消失并且工作正常。 I think that is because I set hovertemplate=[] in the scatterplot.我认为那是因为我在散点图中设置hovertemplate=[] I cannot do that in the candlestick plot because there is no such parameter for it.我不能在烛台 plot 中这样做,因为它没有这样的参数。 Moreover, this icon only appears if I set hovermode='x unified' .此外,仅当我设置hovermode='x unified'时才会出现此图标。 If I set it to x, the little icon doesn't appear.如果我将其设置为 x,则不会出现小图标。 But I need it to be exactly like the tradingview.com example that I showed.但我需要它与我展示的 tradingview.com 示例完全相同。 Is there any way to replicate that crosshair?有没有办法复制那个十字准线?

UPDATE 1:更新 1:

I tried fig.update_layout(hoverdistance=0) .我试过fig.update_layout(hoverdistance=0) But the problem is that when the cursor is not on the candlesticks, the crosshair is just not right.但问题是,当 cursor 不在烛台上时,十字准线不正确。 I took two screenshots: the first one is from tradingview.com charts and the second one is from my code with hoverdistance set to 0.我截了两张截图:第一张来自 tradingview.com 图表,第二张来自我的代码, hoverdistance设置为 0。 在此处输入图像描述 在此处输入图像描述 As can be seen, when the cursor is not on the candlesticks, in the first screenshot the crosshair is still correct.可以看出,当 cursor 不在烛台上时,在第一个屏幕截图中,十字准线仍然正确。 However, in the second screenshot it is just not working correctly.但是,在第二个屏幕截图中,它无法正常工作。 It only works if the cursor is on the candlesticks ONLY.仅当 cursor 仅在烛台上时才有效。 I just want to copy tradingview.com crosshair.我只想复制tradingview.com十字准线。 Nothing less and nothing more.不多也不少。

UPDATE 2:更新 2:

I think the answer could be on these plotly docs .我认为答案可能在这些plotly 文档上。 I am working on it currently.我目前正在研究它。 Please share your comments about this update.请分享您对此更新的意见。

This should do it:这应该这样做:

fig.update_layout(hoverdistance=0)

And setting spikesnap='cursor' for xaxes and yaxes.并为 xaxes 和 yaxes 设置spikesnap='cursor'

These little adjustments will keep the crosshair intact and remove the little icon that has been bothering you.这些小调整将保持十字准线完好无损,并移除一直困扰您的小图标。

From the docs :文档

Plot: Plot:

在此处输入图像描述

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).设置默认距离(以像素为单位)以查找数据以添加 hover 标签(-1 表示不截断,0 表示不查找数据)。 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.对于类似区域的对象(条形、散点填充等),悬停在区域内部和外部关闭,但在发生冲突的情况下,这些对象不会取代点状对象上的 hover。

Complete code: (but with no dash elements)完整代码:(但没有破折号元素)

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

If you set hovermode='x' then you can format the style of the spike line like this:如果你设置hovermode='x'那么你可以像这样格式化尖峰线的样式

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

UPDATE: spikesnap='cursor' will get you closer, but not working exactly for the candlestick.更新: 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)

All the man too complex, the easiest way:所有的人都太复杂了,最简单的方法:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM