pythonplotlynicegui

How do I assign clicked point value to a variable in a Plotly fig in NiceGUI?


Thought I might send this out there for some help before spending too many hours on it. The NiceGUI docs give this simple example:

import plotly.graph_objects as go
from nicegui import ui
    
fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
plot = ui.plotly(fig).classes('w-full h-40')
plot.on('plotly_click', ui.notify)

ui.run()

This works fine for getting a notification. instead of the notification, how do I assign the clicked value to a variable? I know this is easy, but I've tried a few things that didn't work.

First I created a function and called it with the ui.notify method, but that didn't work.

import plotly.graph_objects as go
from nicegui import ui
    
def click_notify():
    ui.notify()

fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
plot = ui.plotly(fig).classes('w-full h-40')
plot.on('plotly_click', click_notify)

ui.run()

First question is, why didn't that work? Second question is, it looks like points.points_ind will get the indices of the selected points, but how to assign that to a variable that NiceGUI will recognize?


Solution

  • The "point_click" event yields GenericEventArguments. You can access the point indices via the dictionary e.args:

    def handle_click(e: events.GenericEventArguments):
        indices = e.args['points'][0]['pointIndex']
        print(f'You clicked on point {indices}')
    
    fig = go.Figure(go.Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 2.5]))
    ui.plotly(fig).on('plotly_click', handle_click)