nicohlr / ipychart

The power of Chart.js with Python
https://nicohlr.github.io/ipychart/
MIT License
108 stars 10 forks source link

Animation with ipywidget #3

Closed ColasDroin closed 2 years ago

ColasDroin commented 2 years ago

Thanks for this amazing library, I'm surprised it's not already super hyped as the plots are looking great, and at the moment there are zero good equivalents for Jupyter notebooks.

It is stated in the doc that a plot could be animated with ipywidget. I tried, but there seems to be no equivalent to the Figure attribute of bqplot, or FigureWidget of plotly, which would be used in e.g. a widgets.VBox object. Here is what I currently have, which doesn't work:

# Modules import
from ipychart import Chart
import ipywidgets as widgets
import time
import numpy as np

# Define data and chart
data = {'datasets': [{'data': [{'x': 0, 'y': 0}, {'x': 1, 'y': 1}]}]}
mychart = Chart(data, 'line')

# Define a button for animation
btn = widgets.Button(description="Start", icon="play")

# Callback to update the chart
def update_chart(btn):
    for i in range(10):
        y = np.random.rand(2)
        with mychart.hold_sync():
            mychart.data = {'datasets': [{'data': [{'x': 0, 'y': y[0]}, {'x': 1, 'y': y[1]}]}]}
        time.sleep(0.1)

btn.on_click(update_chart)

# UI Combining Button & Chart
widgets.VBox([btn, mychart])

I believe I should provide something like mychart.fig instead of mychart to widgets.VBox, but I couldn't find any similar attribute in the Chart class. Any idea how to solve that? If yes, that would be a great addendum to the documentation. Thank you :)

nicohlr commented 2 years ago

Hello @ColasDroin, thank you very much for you feedback :) I'll look into it as soon as I have some time. I would then see if the problem is easy to fix, in which case I would add a patch to the next release. If not, I'll amend the documentation. Either way, I’ll update this issue :)

ColasDroin commented 2 years ago

Many thanks! I just updated the code I posted above as I realised I left some undefined variables.

nicohlr commented 2 years ago

Hello @ColasDroin, the last version of ipychart (0.3.2) should solve this issue :)

For your information, I advise you to use options = {"animation": {"duration": 0}} when updating the chart dynamically to avoid to see an animation at each update.

Please also be careful on how you update the chart : you have to create a new object at each update. The example below illustrate this point :

# This will not work
mychart.data['datasets'][0]['data'][1]["y"] = 1

# This will not work
chart_data = mychart.data
chart_data['datasets'][0]['data'][1]["y"] = 1

# This will work, as we created a new object that we pass to the chart
new_data = copy.deepcopy(mychart.data)
new_data['datasets'][0]['data'][1]["y"] = 1
mychart.data = new_data

Do not hesitate to raise a new issue if you find a bug.