i have problem with animate function.it gives me an empty plot - python

I had some problem with Animate function of matplotlib.
here the code: it gives me an empty graph. maybe i need to dowload some other modules?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
x_data = []
y_data = []
fig, ax = plt.subplots()
ax.set_xlim(0, 105)
ax.set_ylim(0, 12)
line, = ax.plot(0, 0)
def animation_frame(i):
x_data.append(i*10)
y_data.append(i)
line.set_x_data(x_data)
line.set_y_data(y_data)
return line,
ani = animation.FuncAnimantion(fig, func = animation_frame, frames = np.arange(0, 10, 0.01), interval = 10)
plt.show()
the output is:
File "C:\Users\Utente\untitled0.py", line 28, in <module>
ani = animation.FuncAnimantion (fig,func= animation_frame,frames=np.arange(0,10,0.01),interval=10)
*****AttributeError: module 'matplotlib.animation' has no attribute 'FuncAnimantion'*****
with an empty graph!
someone can kindly help me?

There were a few typos:
FuncAnimantion -> FuncAnimation
set_x_data -> set_xdata
set_y_data -> set_ydata
Otherwise it should work:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x_data = []
y_data = []
fig, ax = plt.subplots()
ax.set_xlim(0, 105)
ax.set_ylim(0, 12)
line, = ax.plot(0, 0)
def animation_frame(i):
x_data.append(i * 10)
y_data.append(i)
line.set_xdata(x_data)
line.set_ydata(y_data)
return line,
ani = animation.FuncAnimation(fig, func=animation_frame, frames=np.arange(0, 10, 0.01), interval=10)
plt.show()

Related

How do I make a multi panel plot like this?

I have tried using gridspec, everything looks fine but mi main plot doesn't fill all the space.
[1]: https://i.stack.imgur.com/frHEN.png
[2]: https://i.stack.imgur.com/MA1Sg.png
This is my code:
import h5py
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import transforms
from matplotlib.transforms import Affine2D
import matplotlib.gridspec as gridspec
from FUNCION import *
from FUNCIONAVG import *
f = h5py.File('Datos1', 'r')
list(f.keys())
print(f.keys());
data=f['default'];
data=np.array(data)
fig = plt.figure(1, figsize=(5, 5))
gs = gridspec.GridSpec(8, 8)
gs.update(wspace=0, hspace=0)
xtr_subplot = fig.add_subplot(gs[0:6, 0:2])
base = plt.gca().transData
rot = transforms.Affine2D().rotate_deg(90)
line = plt.plot(sum, transform=rot + base)
plt.ylabel("Y Label")
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
xtr_subplot = fig.add_subplot(gs[0:6, 2:6])
plt.imshow(data, aspect=(6/4))
ax = plt.gca()
ax.axes.yaxis.set_ticklabels([])
xtr_subplot = fig.add_subplot(gs[6:8, 2:6])
plt.plot(avg)
plt.savefig("multipanel.png")
plt.show()
Set the aspect argument of plt.imshow.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import gridspec
from matplotlib import transforms
data = np.random.randn(100).reshape(10, 10)
avg = np.random.randn(10)
total = np.random.randn(10)
fig = plt.figure(1, figsize=(5, 5))
gs = gridspec.GridSpec(8, 8)
gs.update(wspace=0, hspace=0)
xtr_subplot = fig.add_subplot(gs[0:6, 0:2])
base = plt.gca().transData
rot = transforms.Affine2D().rotate_deg(90)
line = plt.plot(total, transform=rot + base)
plt.ylabel("Y Label")
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
xtr_subplot = fig.add_subplot(gs[0:6, 2:6])
plt.imshow(data, aspect=(6 / 4))
ax = plt.gca()
ax.axes.yaxis.set_ticklabels([])
xtr_subplot = fig.add_subplot(gs[6:8, 2:6])
plt.plot(avg)
plt.savefig("multipanel.png")

How to animate a complex function with matplotlib?

I want to make an animation with the function ((phi^n)-((-1/phi)^n))/(5^0.5) (Binet's formula) as n ∈ ℝ,
so that the graph starts as a straight line on the real axes then shifts into the actual graph.
I have tried to add
from matplotlib.animation import FuncAnimation
.
.
.
def g(val):
main_graph.set_ydata(imag(f(x))*val)
return main_graph,
animation = FuncAnimation(main_graph, func=g, frames=arange(0, 10, 0.1), interval=10)
plt.show
However, it did not work and I have no clue why I followed various tutorials and all of them had the same result (An error)
I also tried
import matplotlib.animation as animation
.
.
.
def init():
main_graph.set_ydata([np.nan] * len(real(f(x))))
return main_graph,
def g(val):
main_graph.set_ydata(imag(f(x))*val)
return main_graph,
ani = animation.FuncAnimation(main_graph, g, init_func=init, interval=2, blit=True, save_count=50)
The error, in both cases, is AttributeError: 'Line2D' object has no attribute 'canvas'. Here is the full code
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
plt.legend()
def g(val):
main_graph.set_ydata(imag(f(x))*val)
return main_graph,
animation = FuncAnimation(main_graph, func=g, frames=arange(0, 10, 0.1), interval=10)
plt.show()
To see the final graph use this code
import matplotlib.pyplot as plt
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
plt.legend()
plt.show()
I have adapted the example from matplotlib's animation documentation. Here's how the code has been modified to allow for the modification of axis elements (in this case, the legend) by setting blit=False
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from numpy import arange, real, imag
phi = (1+(5**0.5))/2
x = arange(0,5,0.01)
def f(x):
return ((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)
fig = plt.figure()
main_graph, = plt.plot(real(f(x)),imag(f(x)), label='((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)')
#labels for x and y axes
plt.xlabel('real')
plt.ylabel('imag')
plt.grid(alpha=.4,linestyle=':')
#plt.legend(loc=4)
def init():
global legs
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position(('data', 0.0))
ax.spines['bottom'].set_position(('data', 0))
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_ylim(-4,4)
legs=ax.legend(loc=4, prop={'size': 12})
return main_graph,
def g(val):
main_graph.set_ydata(imag(f(x))*val)
label = '((phi**(x+0j))-((-1/phi)**(x+0j)))/(5**0.5)x{}'.format(val)
legs.texts[0].set_text(label)
return main_graph,
#Note that blit has been set to False, because axes elements are being modified
animation = FuncAnimation(fig, func=g,frames=arange(0, 10, 0.1), init_func=init,interval=10,blit=False)
animation.save('animation.gif', writer='imagemagick', fps=30)
plt.show()
Here's how the animation is:

Matplotlib animation not showing any plot

I am trying to make an animation in 3D using Matplotlib and mpl_toolkits. For starter, I am trying to make an animation of a shifting cos wave. But when I run the program, the plot is completely empty. I have just started learning matplotlib animations, so I don't have in-depth knowledge of it. Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
line, = ax.plot([],[])
print(line)
X = np.linspace(0, 6*math.pi, 100)
def animate(frame):
line.set_data(X-frame, np.cos(X-frame))
return line
anim = animation.FuncAnimation(fig, animate, frames = 100, interval = 50)
plt.show()
Here is the output:
What is wrong with my code? Why am I not getting any output?
There are two issues with your code:
use set_data_3d to update the data of a Line3D object instead of set_data
initialize the Axes3D scales before starting the animation
This should work:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
# initialize scales
ax.set_xlim3d(0, 6 * math.pi)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(0, 100)
X = np.linspace(0, 6 * math.pi, 100)
line, = ax.plot([], [], [])
def animate(frame):
# update Line3D data
line.set_data_3d(X, np.cos(X - frame), frame)
return line,
anim = animation.FuncAnimation(fig, animate, frames = 20, interval = 50)
plt.show()
and yield an animation like this (I have truncated the number of frames to reduce image file size).

How do I get rid of the static graph from matplotlib.animation?

Here's the code that produces an animation using matplotlib. When I run it in Jupyter notebook, I also get another static graph below the animated graph. How do I remove it?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from IPython.display import HTML
fig, ax = plt.subplots()
x = np.arange(0, 20, 0.1)
ax.scatter(x, x + np.random.normal(0, 3.0, len(x)))
line, = ax.plot(x, x - 5, 'r-', linewidth=2)
def update(i):
label = 'timestep {0}'.format(i)
line.set_ydata(x - 5 + i)
ax.set_xlabel(label)
return line, ax
anim = FuncAnimation(fig, update, frames=np.arange(0, 10), interval=200)
HTML(anim.to_html5_video())
I use a module called JSAnimation (see this example notebook from the Author).
To display the animation, you simply call:
from JSAnimation.IPython_display import display_animation
display_animation(anim)

Plot a graph point to point python

I wonder if there is some way to plot a waveform point to point at a certain rate through the matplotlib so that the graph appears slowly in the window. Or another method to graph appears at a certain speed in the window and not all the points simultaneously. I've been tried this but I can only plot a section of points at a time
import numpy as np
import matplotlib.pyplot as plt
import time
x = np.arange(0,5,0.001)
y = np.sin(2*np.pi*x)
ind_i = 0
ind_f = 300
while ind_f <= len(x):
xtemp = x[ind_i:ind_f]
ytemp = y[ind_i:ind_f]
plt.hold(True)
plt.plot(xtemp,ytemp)
plt.show()
time.sleep(1)
ind_i = ind_f
ind_f = ind_f + 300
You can also do this with Matplotlib's FuncAnimation function. Adapting one of the matplotlib examples:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.arange(0,5,0.001)
y = np.sin(2*np.pi*x)
def update_line(num, data, line):
line.set_data(data[..., :num])
return line,
fig = plt.figure()
data = np.vstack((x,y))
l, = plt.plot([], [], 'r-')
plt.xlim(0, 5)
plt.ylim(-1, 1)
line_ani = animation.FuncAnimation(fig, update_line, frames=1000,
fargs=(data, l), interval=20, blit=False)
plt.show()

Categories