gpt4 book ai didi

python - 悬停时仅显示单行,隐藏所有其他行

转载 作者:行者123 更新时间:2023-12-02 18:32:11 27 4
gpt4 key购买 nike

当我将鼠标悬停在单个图形上时,是否有一种方法可以隐藏图形上的所有其他线条?

示例:

import numpy as np
import plotly.express as px

np.random.seed(42)
data = np.random.randint(0, 10, (5, 10))
fig = px.line(data_frame=pd.DataFrame(data))

fig.show()

将产生:

enter image description here

当我悬停特定行时(但无需手动关闭所有其他行并保持 X、Y 轴变暗),我想要这个:

enter image description here

UPD:jupyter 笔记本内部

最佳答案

以下建议取自帖子 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

enter image description here

图 2 - 选择 = 迹线 a

enter image description here

图 3 - 选择 = 迹线 b

enter image description here

完整代码

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)

关于python - 悬停时仅显示单行,隐藏所有其他行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69286545/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com