posit-dev / py-shinywidgets

Render ipywidgets inside a PyShiny app
MIT License
41 stars 2 forks source link

Responding to altair chart selections #112

Open joelostblom opened 8 months ago

joelostblom commented 8 months ago

Does shiny support reactivity/events from making a selection in an interactive chart such as Altair, Plotly, Bokeh, etc? I can't seem to find any examples of this; the closest is the page on "Reacting to widget updates" seem to suggest that shiny only supports events from selections in charts that provide this via an already existing jupyter widgets interaction (such as on_click etc), is this correct?

In Altair, we recently added support for exactly this: chart selections can be accessed in notebooks through a jupyter widget chart object. Based on my understanding this would be supported in shiny too (and maybe even quarto dashboards since they also support jupyter widgets?), but I want to double check if this is the case before trying it out.

I think it could be valuable to add a section on chart selections driving events in the docs, just to be explicit about what works and what doesn't.

Somewhat related issue in https://github.com/posit-dev/py-shiny/issues/768

cpsievert commented 8 months ago

Does shiny support reactivity/events from making a selection in an interactive chart such as Altair, Plotly, Bokeh, etc?

Yes, {shinywidgets}'s reactive_read() function supports reactively reading trait(s) of any ipywidget that supports an .observe() method. In fact, in that "Reacting to widget updates" section you reference, the reactive_read(map, "center") line essentially does a reactive version of map.observe(callback, "center")

Here is how you can leverage reactive_read() to respond to altair selections, in a similar fashion in the link you provided (notice how clicking on the altair legend reactively triggers code to run).

It was slightly tricky to get this working since I was expecting reactive_read(jchart, "selections") to work, but it doesn't since jchart.observe(callback, "selections") doesn't seem to fire callback when the selection changes? Kind of seems like that's oversight/issue on altair's part?

joelostblom commented 8 months ago

This is super, thank you for the detailed example @cpsievert ! I will start experimenting with creating some Shiny + Altair dashboards on my own and see if I run into any limitations, but it looks pretty convenient from your example. I think it would be helpful to add that example to the docs and I also raised the issue you brought up in the Altair repo to see if there is something we can modify there to make the Shiny syntax more convenient.

cpsievert commented 7 months ago

Whoops, this was closed by mistake