以下建议来自Plotly Dash: How to reset the "n_clicks" attribute of a dash-html.button? 和Plotly-Dash: How to code interactive callbacks for hover functions in plotly dash 的帖子,您可以通过将鼠标悬停在线条的任何点或部分上来显示单个跟踪。其余的痕迹并没有完全隐藏,而是在背景中设置为灰色和透明,以便您更轻松地进行其他选择。
要重置图形并同时使所有痕迹完全可见,只需单击Clear Selection。我知道您更喜欢“简单”的 Jupyter 方法来获得此功能,但您会错过 plotly 的真正力量,它只能通过Dash 和JupyterDash 才能充分展示自己。有了这个建议,您不会看到 Dash 和“普通”Jupyter 之间有任何区别,因为图形或应用程序与 app.run_server(mode='inline') 内联显示
情节 1 - 启动时。或点击Clear selection后
情节 2 - 选择 = 跟踪 a
情节 3 - 选择 = 跟踪 b
完整代码
import pandas as pd
import plotly.graph_objects as go
import numpy as np
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from dash.dependencies import Input, Output
from jupyter_dash import JupyterDash
# pandas and plotly settings
pd.options.plotting.backend = "plotly"
# app info
app = JupyterDash(__name__)
# sample data and figure setup
df = pd.DataFrame(np.random.randint(-1,2,size=(200, 12)), columns=list('abcdefghijkl'))
df = df.cumsum()#.reset_index()
fig = df.plot(title = 'Selected traces = all', template='plotly_dark')#.update_traces(line_color = 'rgba(50,50,50,0.5)')
set_fig = go.Figure(fig)
colors = {d.name:d.line.color for i, d in enumerate(set_fig.data)}
# jupyterdash app
app.layout = html.Div([html.Button('Clear selection', id='clearit', n_clicks=0),
dcc.Graph(id='hoverfig',figure=fig,#clear_on_unhover = True
),])
colors = {d.name:d.line.color for i, d in enumerate(set_fig.data)}
# callbacks
@app.callback(
Output('hoverfig', 'figure'),
[Input('hoverfig', 'hoverData'), Input('clearit', 'n_clicks')])
def display_hover_data(hoverData, resetHover):
changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
if 'clearit' in changed_id:
return set_fig
else:
try:
fig2 = fig.update_layout(title = 'Selected trace = ' + fig.data[hoverData['points'][0]['curveNumber']].name)
fig2.for_each_trace(lambda t: t.update(line_color = 'rgba(50,50,50,0.5)',line_width = 1) if t.name != fig.data[hoverData['points'][0]['curveNumber']].name else t.update(line_color = colors[t.name], line_width = 2))
return fig2
except:
return fig
app.run_server(mode='inline', port = 8070, dev_tools_ui=True,
dev_tools_hot_reload =True, threaded=True)