How do I animate this graph so that the dot moves and the green line plots over a different range for each element in loop?

669 Views Asked by At

I am trying to make this animated so that the dot and the green line move due to the for loop. This code displays 3 different graphs one below the other. The middle graph has no animation section.

x =lag_range
count = 0
plt.ion()
fig, ax = plt.subplots()
for b in x:

    plt.subplot(311)
    plt.plot(x,pear_corr, color='b', linewidth=1.5, label ='Pearson')
    plt.plot(x,spear_corr, color ='r', linewidth=1.5, label='Spearman')
    plt.plot(x[count],pear_corr[count],'yo')
    plt.legend()    
    axes = plt.gca()
    plt.ylabel('Correlation coefficients')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])
    axes.set_ylim(-1,1)

    plt.subplot(312)
    plt.plot(x,pear_p_values, color='b', linewidth=1.5)
    plt.plot(x,spear_p_values, color ='r', linewidth=1.5)   
    axes = plt.gca()
    plt.ylabel('P values')
    plt.xlabel('Lag times /days')
    axes.set_xlim([min(lag_list),last])

    plt.subplot(313)
    ax1 = plt.subplot(313)
    x_for_p = range(len(x_prices))
    ax1.plot(x_for_p, x_prices, color ='grey', linewidth=1.5)
    ax1.set_ylabel('Share price', color ='grey')
    ax1.tick_params('y', colors='grey')
    ax1.set_xlabel('Days')
    axes = plt.gca()
    axes.set_xlim([min(lag_list),(2*last)])

    ax2 = ax1.twinx()
    x_for_den = range(b,(b+len(x_prices)))
    ax2.plot(x_for_den, y_planes, color='g', linewidth=1.5)
    ax2.set_ylabel('Plane density', color='g')
    ax2.tick_params('y', colors='g')

    count += 1
    plt.pause(2)
    plt.draw()

cross_corr2_vis(prices, density_p3)

1

There are 1 best solutions below

0
pch On

If you could share a working code or just definitions of variables pear_corr, spear_corr, etc., the following code might have not resulted in this simple animation:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

N_points = 1000

x = np.linspace(0,2.*np.pi,N_points)
y = np.sin(x)

fig, ax = plt.subplots()
ax.set_xlim([0,2.*np.pi])
ax.set_ylim([-1,1])
line, = ax.plot(   [],[], lw=2,  color='g')
sctr  = ax.scatter([],[], s=100, color='r')

def animate(i):
    line.set_ydata(y[:i+1])  # update
    line.set_xdata(x[:i+1])
    sctr.set_offsets((x[i],y[i]))
    return line,sctr

ani = animation.FuncAnimation(fig, animate, N_points, interval=5, blit=True)
plt.show()