0

I am trying to animate a one-dimensional function where the function inputs are same but function parameters are changing with time. The function I am trying to animate is

f(x)=sin(a* pi * x)/(b*x)+ (x-1)^4

Here the data to be plotted is same, but a, b are changing with every update.I am using python and matplotlib library. My initial attempt is as follows:

fig,ax = plt.subplots()
line, = ax.plot([],[])

def animate(i,func_params):
    x = np.linspace(-0.5,2.5,num = 200)
    a=func_params[i][0]
    b=func_params[i][1]
    y=np.sin(a*math.pi*x)/b*x + (x-1)**4
    line.set_xdata(x)
    line.set_ydata(y)
    return line,

ani = animation.FuncAnimation(fig,animate,frames=len(visualize_pop),fargs=(visualize_func,),interval = 100,blit=True)
plt.show()

The above code is not plotting anything.

EDIT: Updated code based on comment.

1 Answers1

-1

Your problem is that with plot([],[]) you give matplotlib no data and therefore no way do determine the limits of the axes. Therefore it uses some default values which are way out of the range of the data you actually want to plot. Therefore you have two choices:

1) Set the limits to some values that will contain all your plotted data for all cases, e.g.

ax.set_xlim([-0.5,2.5])
ax.set_ylim([-2,6])

2) Let ax compute the limits automatically each frame and re-scale the plot see here using these two commands within your animate function (note that this option only works correctly if you turn blitting off):

ax.relim()
ax.autoscale_view()

Here still a completely working version of your code (the commands for solution (1) are commented out and I changed some of the notations):

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

fig,ax = plt.subplots()
x = np.linspace(-0.5,2.5,num = 200)
line, = ax.plot([],[])

#ax.set_xlim([-0.5,2.5])
#ax.set_ylim([-2,6])

##assuming some parameters, because none were given by the OP:
N = 20
func_args = np.array([np.linspace(1,2,N), np.linspace(2,1,N)])

def animate(i,func_params):
    a=func_params[0,i]
    b=func_params[1,i]
    y=np.sin(a*np.pi*x)/b*x + (x-1)**4
    line.set_xdata(x)
    line.set_ydata(y)
    ax.relim()
    ax.autoscale_view()
    return line, ax

##blit=True will not update the axes labels correctly
ani = FuncAnimation(
    fig,animate,frames=N, fargs=(func_args,),interval = 100 #, blit=True
)
plt.show()
Thomas Kühn
  • 9,412
  • 3
  • 47
  • 63