# Damodar Rajbhandari (2022)
import matplotlib
matplotlib.rcParams['text.usetex'] = True # uncomment if you donot have latex installed
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import rc
from IPython.display import Image
rc('animation', html='html5')
plt.rcParams.update({'font.size': 13})
# animate point P = alpha0 * v0 + alpha1 * v1 + alpha2 * v2
fig = plt.figure(figsize=(10, 10))
fig.tight_layout()
pls = []
x = [2, 4, 12]
y = [1,7, 6]
plt.plot(x, y, 'o', color='black')
# plot dots with labels v0, v1, v2
for i in range(3):
plt.text(x[i]-.37, y[i]+.1, '$v_'+str(i)+'$')
plt.text(1.5, 8, '$P := \\alpha^0 v_0 + \\alpha^1 v_1 + \\alpha^2 v_2$')
plt.fill(x, y, color='green', alpha=0.3)
plt.xlim(0, 15)
plt.ylim(0, 9)
for alpha1 in np.arange(-0.1, 1.2, 0.1):
for alpha2 in np.arange(-0.2, 1, 0.1):
alpha3 = 1 - alpha1 - alpha2
if alpha3 >= 0:
x = alpha1 * 2 + alpha2 * 4 + alpha3 * 12
y = alpha1 * 1 + alpha2 * 7 + alpha3 * 6
pl, = plt.plot(x, y, 'o', color='red')
npl = plt.text(x-.35, y+.1, 'P')
a1 = plt.text(1.5, 8.5, '$\\alpha^0$ = '+str(round(alpha1, 2)))
a2 = plt.text(4.5, 8.5, '$\\alpha^1$ = '+str(round(alpha2, 2)))
a3 = plt.text(7.5, 8.5, '$\\alpha^2$ = '+str(round(alpha3, 2)))
a1a2a3 = plt.text(10.5, 8.5, '$\\alpha^0 + \\alpha^1 + \\alpha^2$ = '+str(round(alpha1+alpha2+alpha3, 2)))
myp = plt.text(5.3, 8, '$ = '+str(round(alpha1, 2))+r'\left(\begin{array}{c} 2 \\ 1 \end{array}\right) + '+str(round(alpha2, 2))+r'\left(\begin{array}{c} 4 \\ 7 \end{array}\right) + '+str(round(alpha3, 2))+r'\left(\begin{array}{c} 12 \\ 6 \end{array}\right) = '+r'\left(\begin{array}{c}'+str(round(x, 2))+r'\\'+str(round(y, 2))+r'\end{array}\right)$')
pls.append([pl, npl, a1, a2, a3, a1a2a3, myp])
# make a trace dashes line of previous points
for i in range(len(pls)-1):
plt.plot([pls[i][0].get_xdata()[0], pls[i+1][0].get_xdata()[0]], [pls[i][0].get_ydata()[0], pls[i+1][0].get_ydata()[0]], '--', color='red')
# create the animation
ani = animation.ArtistAnimation(fig, pls, interval=50, blit=True)
ani.save('convex-combination.gif', writer='imagemagick', fps=70)
with open('convex-combination.gif','rb') as f:
display(Image(data=f.read(), format='png'))