Skip to content

Hover labels solution using JavaScript #5532

@Sravanthi-Gogadi

Description

@Sravanthi-Gogadi

Can someone please provide a clear example for this? I am having difficulty in implementing this logic.

I tried the same one but no luck
@eddy-geek @chriddyp

So, after digging a bit, here is a solution that works for me, based on great work by others in the community.

The main tricks are

  • dynamically get plot names
  • use visdcc.Runjs to reload the javasript on graph change, to reattach the event handler to the re-created plot. (other approaches like setTimeout and dash_defer_js_import work the first time only)
JS_STR = '''

var plotid = 'theplotname'
var plot = document.getElementById(plotid)

plot.on(
  'plotly_hover',
  function (eventdata) {
    Plotly.Fx.hover(
      plotid,
      { xval: eventdata.xvals[0] },
      Object.keys(plot._fullLayout._plots) // ["xy", "xy2", ...]
    );
  });
'''

layout = html.Div([
    dcc.Graph(id='theplotname'),
    visdcc.Run_js(id='hover-js')  # <-- add this
])

@app.callback(
    [Output('theplotname', 'figure'),
     Output('hover-js', 'run'),  # <-- add this
    ], [... inputs...])
def foo(inputs):
    figure = ...
    fig.update_layout(hovermode='x')   # "compare"
    return figure, JS_STR  # <-- add this

image

Originally posted by @eddy-geek in #2114 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions