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

标签 python plotly plotly-python

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

示例:

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/

相关文章:

python - tensorflow 中是否有与list.append()类似的函数?

python - 对 plotly 在线/离线/袖扣和不同版本感到困惑

python - 设置 Plotly Bar graph x 轴的对齐方式

r - R图上的纸张边框

python - 我可以计算 p 值并使用 plotly 添加星号吗?

python - 尝试调用 self 时出现扭曲错误

python - Flask APP - ValueError : signal only works in main thread

python - 云 Composer /Airflow : Relationships can only be set between Operators; received PythonOperator

plotly - 添加 Plotly Modebar 按钮,允许切换悬停模式

Plotly Treemap 不能与 go.Treemap 一起使用,但可以与plotly.express 一起使用吗?