I am wanting to use matplotlib.annimation to sequentially plot data points and plot vertical lines as they become known.
What I have at the moment is the following:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
x = np.arange(len(data))
y = data
fig = plt.figure()
plt.xlim(0, len(data))
plt.ylim(-8, 8)
graph, = plt.plot([], [], 'o')
def animate(i):
# line_indicies = func(x[:i+1])
graph.set_data(x[:i+1], y[:i+1])
# then I would like something like axvline to plot a vertical line at the indices in line indices
return graph
anim = FuncAnimation(fig, animate, frames=100, interval=200)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
I would like to plot vertical lines outputted from a function as described in the comments in the animate function.
The lines are subject to change as more data points are processed.
I wrote the code with the understanding that I wanted to draw a vertical line along the index of the line graph. I decided on the length and color of the vertical line, and wrote the code in OOP style, because if it is not written in ax format, two graphs will be output.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
data = np.random.randint(-8,8,(100,))
x = np.arange(len(data))
y = data
fig = plt.figure()
ax = plt.axes(xlim=(0, len(data)), ylim=(-8, 8))
graph, = ax.plot([], [], 'o')
lines, = ax.plot([],[], 'r-', lw=2)
def init():
lines.set_data([],[])
return
def animate(i):
graph.set_data(x[:i+1], y[:i+1])
# ax.axvline(x=i, ymin=0.3, ymax=0.6, color='r', lw=2)
lines.set_data([i, i],[-3, 2])
return graph
anim = FuncAnimation(fig, animate, frames=100, interval=200)
# anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
Related
I have used .set_data() method/function to update co-ordinate of the line after every frame. x1,y1 values are being updated but they are not being update in the line plot. What am I doing wrong here?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(6,6)
ax=plt.axes(xlim=(-10,10), ylim=(-10,10))
l1, = ax.plot([0.0, 1.0],[0.0,5.0], color = 'b', linewidth = 1)
def animate(i):
x1=np.sin(np.radians((i)+90))
y1=np.cos(np.radians((i)+90))
l1.set_data=([0,x1],[0,y1])
#print (x1,y1)
return l1,
anim = animation.FuncAnimation(fig, animate, frames=360, interval=20, blit=True)
plt.show()
You wrote l1.set_data=([0,x1],[0,y1]). Is that a typo? This should be (notice the removal of the = sign):
l1.set_data([0,x1],[0,y1])
I have my data file containing x,y coordinates of a fractal. I want to get a animation of this coordinates.
I have tried this code.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
data1=np.loadtxt('data.txt')
fig = plt.figure()
ax = plt.axes()
scat = ax.scatter([], [])
def init():
scat.set_offsets([])
return scat
def animate(i):
scat.set_offsets(data1)
return scat
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=700, interval=1, blit=True)
plt.show()
Error is 'PathCollection' object is not iterable.
I don't know much, any help will be thankful.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure(1)
ax1 = fig.add_subplot(1,1,1)
def animate(i):
graph_data = open('example.txt','r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs, ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Is there another way to write the code such that y-axis is in ascending order?
If so. where should I find it? This is from sentdex matplotlib tutorial
The better solution is to not do all the stuff manually and rely on numpy reading the data. Also, not clearing the axes in each loopstep may be beneficial.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
line, = ax.plot([],[])
def animate(i):
x,y = np.loadtxt("data/example.txt", unpack=True, delimiter=",")
line.set_data(x,y)
ax.relim()
ax.autoscale_view()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
I want to plot in 3D using matplotlib (python), which data is added in real time(x,y,z).
In the below code, data appends on x-axis and y-axis successfully, but on z-axis I've encountered problems.although I've searched in matplotlib's docs, I could not find any solutions.
what should be added/changed to this code to make it append data in z-axis?
what works correctly:
return plt.plot(x, y, color='g')
problem:
return plt.plot(x, y, z, color='g')
Code:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
import random
np.set_printoptions(threshold=np.inf)
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = []
y = []
z = []
def animate(i):
x.append(random.randint(0,5))
y.append(random.randint(0,5))
z.append(random.randint(0,5))
return plt.plot(x, y, color='g')
#return plt.plot(x, y, z, color='g') => error
ani = animation.FuncAnimation(fig, animate, interval=1000)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('z')
plt.show()
How to get this done correctly?
The plotting method you want to use for 3D plots is the one from the Axes3D. Hence you need to plot
ax1.plot(x, y, z)
However, it seems you want to update the data instead of plotting it all over again (making the line look somehow rasterized, as it would consists of all the plots).
So you can use set_data and for the third dimension set_3d_properties. Updating the plot would look like this:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
x = []
y = []
z = []
line, = ax1.plot(x,y,z)
def animate(i):
x.append(np.random.randint(0,5))
y.append(np.random.randint(0,5))
z.append(np.random.randint(0,5))
line.set_data(x, y)
line.set_3d_properties(z)
ani = animation.FuncAnimation(fig, animate, interval=1000)
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_zlabel('z')
ax1.set_xlim(0,5)
ax1.set_ylim(0,5)
ax1.set_zlim(0,5)
plt.show()
I am trying to implement a live graph, however, my x and y axis are not showing up. Ive tried placing it in multiple areas of the code, however, none of those methods were successful.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
style.use('fivethirtyeight')
fig = plt.figure()
plt.xlabel('Time (s)')
plt.ylabel('Temperature (F)')
plt.title("Your drink's current temperature")
plt.xlabel('xlabel', fontsize=10)
plt.ylabel('ylabel', fontsize=10)
ax1 = fig.add_subplot(1,1,1)
def animate(i):
plt.xlabel('xlabel', fontsize=10)
plt.ylabel('ylabel', fontsize=10)
graph_data = open('plot.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(y)
ax1.clear()
ax1.plot(xs,ys)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
Here is the data file that I am reading from (plot.txt):
0,27.00
1,68.85
2,69.30
3,69.30
4,69.30
5,69.75
6,70.20
7,69.75
8,69.75
9,69.30
10,69.75
11,69.75
12,69.75
13,69.75
14,70.20
15,69.75
16,69.75
17,69.75
18,69.75
19,68.85
20,69.75
21,69.75
22,69.75
23,69.30
The problem is that you are calling clear in your animation function. You want to just update an existing artist (and let the animation code take care of re-drawing it as needed)
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as manimation
fig, ax = plt.subplots()
ax.set_xlabel('Time (s)')
ax.set_ylabel('Temperature (F)')
ax.set_title("Your drink's current temperature")
xs = np.linspace(0, 2*np.pi, 512)
ys = np.sin(xs)
ax.set_xlim(0, 2*np.pi)
ax.set_ylim(-1, 1)
ln, = ax.plot([], [], lw=3)
def init(*args, **kwargs):
ln.set_data([], [])
return ln,
def animate(i):
ln.set_data(xs[:i], ys[:i])
return ln,
ani = manimation.FuncAnimation(fig, animate,
frames=512, blit=True,
init_func=init)
plt.show()
if you need to read in from another data source (ex, your file) just read it and then set the data on your line.