Fit

This example uses the draw() and tween() animations to animate a scatter, plot, fill_between and text plot objects.

We first create our timeline and name our axes:

import diplotocus as dpl
import numpy as np

tl = dpl.Timeline(xlim=(0,1),ylim=(0,1.5))
tl.main_axis.set_xlabel('x')
tl.main_axis.set_ylabel('y')

Then, we create the data we want to plot (data points, the fitted relation and its uncertainty):

x = np.random.uniform(0,1,100)
y = np.random.normal(0.5*(1+x),0.2)

popt, cov = np.polyfit(x,y,1,cov=True)
err = np.sqrt(np.diag(cov))

#Cheap & dirty way to get confidence bounds with numpy
p_rand = np.random.normal(size=(10_000,2))*err + popt
_x = np.linspace(0,1,1_000)
_y = popt[0]*_x + popt[1]
_ys = []
for _p in p_rand:
    _ys.append(_p[0]*_x + _p[1])
y_max = np.max(_ys,axis=0)
y_min = np.min(_ys,axis=0)

And finally, we animate it and render the video. To animate the confidence bounds growing, we start the fill_between’s y1 and y2 properties from the same y values as the line, and we tween them to y_min and y_max, the actual size of the \(\pm 1\sigma\) bounds.

e = dpl.easeInOutCubic()
s = dpl.scatter(x=x,y=y)
p = dpl.plot(x=_x,y=_y,c='k',lw=3)
t = dpl.text(x=0.05,y=1.2,string=f'f(x) = {popt[0]:.2f}x + {popt[1]:.2f}',fontsize=14)
f = dpl.fill_between(x=_x,y1=_y,y2=_y,alpha=0.2,fc='green')

s.draw(duration=60,sort='x',easing=e)
p.draw(duration=60,delay=60,easing=e)
t.draw(duration=60,delay=60,easing=e)
f.tween(property='y1',start=_y,end=y_min,duration=60,delay=120,easing=e)
f.tween(property='y2',start=_y,end=y_max,duration=60,delay=120,easing=e)

tl.animate((s,p,t,f))
tl.wait(duration=60)

tl.save_video('../../_static/examples/fit.mp4')