Multiple vertical cursors for harmonics search

Hi everyone,

I use Plotly Python to produce graphs to help me analyse acoustics data.
I plot spectrums on a graph.

I would now like to improve it by adding harmonics cursors to help visualize harmonics on my graph.

I already managed to add one cursor as shown below but the idea here would be to have 10 cursors for example and have all of them move with the first one.
Let’s say the first one is at a x value of f1=150Hz. The second one should always be at f2=2150Hz, the third one at f3=3150Hz, etc…

The cursor on the image moves automatically with my mouse when I hover over the graph.
I added this cursor with this line of code:

fig.update_xaxes(
    showspikes=True,
    spikecolor="green",
    spikesnap="cursor",
    spikemode="across",
    spikedash="solid",
)

If needed I can provide the rest of the code but I am not sure it is needed for this question.

Thanks in advance

Antoine

Hi @Antoine101 I don’t think there is a built-in function for this.

If you’re open to use dash there is a solution.

Hi AIMPED,

Thanks for your reply!
I am open to it yes.

Could you explain a bit more or point me to this solution you’re talking about please?

Cheers

Antoine

Sure, that’s what I had in mind:

from dash import Dash, html, dcc, Output, Input, Patch
import plotly.graph_objects as go

app = Dash(
    __name__,
    external_stylesheets=[
    ]
)


def create_shapes(*positions):

    shapes = [
        {'type': 'line',
         'x0': pos,
         'x1': pos,
         'xref': 'x',
         'y0': 0,
         'y1': 1,
         'yref': 'y domain'
         }
        for pos in positions
    ]

    return shapes


app.layout = html.Div(
    [
        dcc.Graph(
            id='graph',
            figure=go.Figure(
                go.Scatter(
                    x=[*range(20)],
                    y=[*range(20)],
                    mode='markers+lines'
                )
            )
        ),
    ]
)


@app.callback(
    Output('graph', 'figure'),
    Input('graph', 'hoverData'),
    prevent_initial_call=True
)
def update(hoverData):
    # get hover coordinate in x direction
    x = hoverData['points'][0]['x']
    patched = Patch()

    # add vertical lines, in this case three
    # the relative distance to the hover coordinate is hard coded (1 and 2)
    patched['layout']['shapes'] = create_shapes(x, x + 1, x + 2)

    return patched


if __name__ == '__main__':
    app.run(debug=True)

Just tried it out and it does the job perfectly! In the case of harmonics I would just change create_shapes(x, x + 1, x + 2) to create_shapes(x, 2*x, 3*x) but that’s just a detail.

Thank you so much for your help AIMPED!

1 Like

A post was merged into an existing topic: Linked Graphs from x-y scatter to x vs t and y vs t