Thursday, 4 December 2014

Animated graphs with matplotlib

Recently I have had not so much time to dedicate to my blog, however, today I had some spare time and decided to learn how to code animated graphs with Python and matplotlib.
Apparently it’s really simple, however a little bit of practice is needed, here below are three pieces of code where I coded and plotted the graph of (many) branch of parabolas, a random walk, and a simulated stock (a random walk again!).
Here is the half parabolas



import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
x = [i for i in range(20)]
y = [np.sqrt(i**3) for i in x]
def animate(i):
global x,y
r = np.random.normal(0,1,1)
xar = x
yar = y + r*y
#ax1.clear()
ax1.plot(xar,yar,marker='o')
ani = animation.FuncAnimation(fig,animate,interval=1000)
plt.show()


Below is the random walk and the video:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def randomWalk():
r = np.random.normal(0,1,1)
if r < 0:
return -1
elif r > 0:
return 1
else:
return 0
counter = 0
start = [0]
t = [0]
def animate(i):
global t,u,sd,counter
x = t
y = start
counter += 1
x.append(counter)
y.append(start[counter-1] + randomWalk())
plt.plot(x[counter-1],y[counter-1],marker='o',color="r")
ani = animation.FuncAnimation(fig,animate,interval=1)
plt.show()

video of the random walk: https://www.youtube.com/watch?v=3pAHwt1ioz4

and finally the stock simulation:


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def getNewPrice(s,mean,stdev):
r = np.random.normal(0,1,1)
priceToday = s + s*(mean/255+stdev/np.sqrt(225)*r)
return priceToday
z = np.random.normal(0,1,255)
u = 0.1
sd = 0.3
counter = 0
price = [100]
t = [0]
def animate(i):
global t,u,sd,counter
x = t
y = price
counter += 1
x.append(counter)
y.append(getNewPrice(price[counter-1],u,sd))
ax1.clear()
plt.plot(x,y,color="blue")
ani = animation.FuncAnimation(fig,animate,interval=50)
plt.show()


Hope this was interesting Sorriso.

2 comments:

  1. Thanks for sharing the descriptive information on Python tutorial. It’s really helpful to me since I'm taking Python training. Keep doing the good work and if you are interested to know more on Python, do check this Python tutorial.:-https://www.youtube.com/watch?v=HcsvDObzW2U

    ReplyDelete