Hi I'm having trouble in getting matplotlib animation to work
The idea is to animate throughout a few lists and images.
a[0] is basically time points/images to plot/imshow
"timepoints[a[0].astype(np.int)][:i]/60" is simply the indexed "real time" to be in the x axis
May anyone give me some hints?
Appreciated
def draw_plot(resolution,timepoints,a,ts_g,ts_r,contrast):
def animate(i):
#~ ax.cla()
#~ ax2.cla()
#~ ax3.cla()
#~ ax4.cla()
print "ax"
ax.errorbar(timepoints[a[0].astype(np.int)][:i]/60,list(a[1][0])[:i], yerr=list(a[4][0])[:i], fmt='-o',color='green')
ax.errorbar(timepoints[a[0].astype(np.int)][:i]/60,list(a[1][1])[:i], yerr=list(a[4][1])[:i], fmt='-o',color='red')
ax.axis([0,timepoints[a[0].astype(np.int)][-1]/60,np.min(np.concatenate((a[1][0],a[1][1])))*0.75,np.max(np.concatenate((a[1][0],a[1][1])))*1.3])
ax.set_autoscale_on(False)
print "ax2"
ax2.plot(timepoints[a[0].astype(np.int)][:i]/60,list(a[2][0])[:i],color='green')
ax2.plot(timepoints[a[0].astype(np.int)][:i]/60,list(a[2][1])[:i],color='red')
ax2.axis([0,timepoints[a[0].astype(np.int)][-1]/60,np.min(np.concatenate((a[2][0],a[2][1])))*0.75,np.max(np.concatenate((a[2][0],a[2][1])))*1.3])
ax2.set_autoscale_on(False)
j = int(a[0][i]-1)
r = ts_r[j]#.T
g = ts_g[j]#.T
max_ = contrast[3]
min_ = contrast[2] #~
r[r>max_]=max_
r[r<min_]=min_
r -= min_
r *= _16bit/(max_-min_)#r.max()
max_ = contrast[1]
min_ = contrast[0]
g[g>max_]=max_
g[g<min_]=min_
g -= min_
g *= _16bit/(max_-min_)#r.max()
#~
g_16 = g
r = (r*ratio).astype(np.uint8)
g = (g*ratio).astype(np.uint8)
b = np.zeros(r.shape).astype(np.uint8)
centered = np.dstack((r,g,b)).astype(np.uint8)
#~ aa = np.dstack((np.zeros(ts[0].shape).T,ts[j].T,np.zeros(ts[0].shape)))
print "ax3"
ax3.imshow(centered)
ax3.plot(list(a[5][0]/resolution)[:i],list(512-a[5][1]/resolution)[:i],color='blue')
ax3.axis([0,512,512,0])
print "ax4"
ax4.imshow(centered)
x = int (list(a[5][0]/resolution)[i])
y = int (list(512-a[5][1]/resolution)[i])
#~ ax4.axis([512,0,512,0])
ax4.axis([x-10,x+10,y-10,y+10])
ax4.get_xaxis().set_visible(False)
ax4.get_yaxis().set_visible(False)
print "ax5"
ax5.imshow(g_16,cmap='gray')
#~ x = int (list(a[5][0]/resolution)[i])
#~ y = int (list(512-a[5][1]/resolution)[i])
#~ ax4.axis([512,0,512,0])
ax5.axis([x-10,x+10,y-10,y+10])
ax5.get_xaxis().set_visible(False)
ax5.get_yaxis().set_visible(False)
plt.draw()
fig = plt.figure()
ax = plt.subplot2grid((2,5), (0,0),colspan=2)
ax2 = plt.subplot2grid((2,5), (1,0),colspan=2)
ax3 = plt.subplot2grid((2,5), (0, 2), colspan=2,rowspan=2)
ax4 = plt.subplot2grid((2,5), (0,4))
ax5 = plt.subplot2grid((2,5), (1, 4))
line, = ax.plot([], [], lw=2)
line2, = ax2.plot([], [], lw=2)
ani = animation.FuncAnimation(fig, animate, frames= len(a[0]), interval=20000,repeat=False,blit=True)
plt.show()
Alright, like this it works.
However:
1- I can't return the list with several axes/lines (lines = [] ) I have to return each one individually (errorline_g, etc, etc).It works with normal ax.plots, so I don't know why errorbars can't do the same.
same with Vertical bars. I had to use errorline_g, ( bottomsg,topsg), (vertsg, )= ax.errorbar([],[],yerr=1,fmt='-o',color='green')
If I don't unpack the tuple at declaration if I would try to return vertsg or vertsg[0] it doesn't work.
def draw_plot(resolution,timepoints,a,ts_g,ts_r,contrast,csvfile):
fig = plt.figure()
ax = plt.subplot2grid((2,5), (0,0),colspan=2)
ax2 = plt.subplot2grid((2,5), (1,0),colspan=2)
ax3 = plt.subplot2grid((2,5), (0, 2), colspan=2,rowspan=2)
ax4 = plt.subplot2grid((2,5), (0,4))
ax5 = plt.subplot2grid((2,5), (1, 4))
ax.axis([0,(timepoints[a[0].astype(np.int)-1][-1]/60)+5,np.min(np.concatenate((a[1][0],a[1][1])))*0.75,np.max(np.concatenate((a[1][0],a[1][1])))*1.3])
ax.set_autoscale_on(False)
ax2.axis([0,(timepoints[a[0].astype(np.int)-1][-1]/60)+5,np.min(np.concatenate((a[2][0],a[2][1])))*0.75,np.max(np.concatenate((a[2][0],a[2][1])))*1.3])
ax2.set_autoscale_on(False)
#~ ax3.axis([0,512,512,0])
ax3.get_yaxis().set_visible(False)
ax4.get_xaxis().set_visible(False)
ax4.get_yaxis().set_visible(False)
ax5.get_xaxis().set_visible(False)
ax5.get_yaxis().set_visible(False)
errorline_g, ( bottomsg,topsg), (vertsg, )= ax.errorbar([],[],yerr=1,fmt='-o',color='green')
errorline_r, ( bottomsr,topsr), (vertsr, ) = ax.errorbar([],[],yerr=1,fmt='-o',color='red')
lines = []
lines += ax2.plot([],[], color='green', lw=2)
lines += ax2.plot([],[], color='red', lw=2)
lines += ax3.plot([],[],color='blue')
def animate(i=0):
#~ ax.cla()
#~ ax2.cla()
#~ ax3.cla()
#~ ax4.cla()
x = timepoints[a[0].astype(np.int)][:i+1]/60
y = list(a[1][0])[:i+1]
g_berr = np.array(a[1][0])[:i+1]+np.array(a[4][0])[:i+1]
g_terr = np.array(a[1][0])[:i+1]-np.array(a[4][0])[:i+1]
r_berr =np.array(a[1][1])[:i+1]+np.array(a[4][1])[:i+1]
r_terr =np.array(a[1][1])[:i+1]-np.array(a[4][1])[:i+1]
errorline_g.set_data(x,y)
bottomsg.set_data(x,g_berr)
topsg.set_data(x,g_terr)
vertsg.set_segments(zip(zip(x,g_terr),zip(x,g_berr)))
#~ ax.errorbar(timepoints[a[0].astype(np.int)][:i]/60,list(a[1][1])[:i], yerr=list(a[4][1])[:i], fmt='-o',color='red')
ax.fill_between(x, g_berr, g_terr,
alpha=0.05, edgecolor='green', facecolor='green')
#~ print errorline_g
y = list(a[1][1])[:i+1]
errorline_r.set_data(x,y)
bottomsr.set_data(x,r_berr)
topsr.set_data(x,r_terr)
ax.fill_between(x, r_berr, r_terr,
alpha=0.08, edgecolor='red', facecolor='red')
vertsr.set_segments(zip(zip(x,r_terr),zip(x,r_berr)))
lines[0].set_data(timepoints[a[0].astype(np.int)][:i+1]/60,list(a[2][0])[:i+1])
lines[1].set_data(timepoints[a[0].astype(np.int)][:i+1]/60,list(a[2][1])[:i+1])
j = int(a[0][i]-1)
r = ts_r[j]#.T
g = ts_g[j]#.T
max_ = contrast[3]
min_ = contrast[2] #~
r[r>max_]=max_
r[r<min_]=min_
r -= min_
r *= _16bit/(max_-min_)#r.max()
max_ = contrast[1]
min_ = contrast[0]
g[g>max_]=max_
g[g<min_]=min_
g -= min_
g *= _16bit/(max_-min_)#r.max()
g_16 = g
r = (r*ratio).astype(np.uint8)
g = (g*ratio).astype(np.uint8)
b = np.zeros(r.shape).astype(np.uint8)
centered = np.dstack((r,g,b)).astype(np.uint8)
ax3.imshow(centered)
lines[2].set_data(list(a[5][0]/resolution)[:i],list(512-a[5][1]/resolution)[:i])
#~ ax3.axis([0,512,512,0])
ax4.imshow(centered)
x = int (list(a[5][0]/resolution)[i])
y = int (list(512-a[5][1]/resolution)[i])
#~#
ax4.axis([x-10,x+10,y-10,y+10])
ax5.imshow(g_16,cmap='gray')
ax5.axis([x-10,x+10,y-10,y+10])
#~ plt.draw()
return errorline_g, errorline_r, lines[0], lines[1],lines[2],bottomsg,topsg,bottomsr,topsr,ax,ax2,ax3,ax4,ax5,vertsg
def init():
errorline_g.set_data([],[])
errorline_r.set_data([],[])
for line in lines:
line.set_data([],[])
#~ lines[0].set_data([],[])
#~ lines[1].set_data([],[])
ax3.imshow(np.zeros(ts_r[0].shape))
ax4.imshow(np.zeros(ts_r[0].shape))
ax5.imshow(np.zeros(ts_r[0].shape))
return errorline_g, errorline_r, lines[0], lines[1], lines[2],ax,ax2,ax3,ax4,ax5
ani = animation.FuncAnimation(fig, animate, init_func=init, frames= len(a[0]), interval=500,repeat=False,blit=True)
plt.show()
#~ ani.save('./mp4/'+csvfile.strip('.csv').strip('./')+".mp4")
plt.close()
Related
def nonuniform_poly_interpolation(a,b,p,n,x,f,produce_fig):
xhat = np.zeros(p+1)
for j in range(p+1):
xhat[j] = b - a + a * np.cos(np.pi * (((2*j)+1)/(2*(p+1))))
lagrange_matrix = lagrange_poly(p,xhat,n,x,1e-10)
nu_interpolant = np.empty(n)
for i in range(p+1):
nu_interpolant[i] = nu_interpolant[i] + (f(xhat[i]) * lagrange_matrix[i]);
fig = plt.figure()
plt.plot(x,f(x), label = "f(x)")
plt.plot(x,nu_interpolant, label = "Pp(x)")
plt.legend(loc = "upper left")
plt.xlabel("x")
plt.ylabel("Pp(x)")
plt.title("Nonuniform Polynomial Interpolation")
plt.show()
if produce_fig == True:
fig = fig
else:
fig = None
return nu_interpolant, fig
Not sure what "ValueError: setting an array element with a sequence" means and how I could fix this code? It is sensing an error on line 127 (for i in range(p+1):
nu_interpolant[i] = nu_interpolant[i] + (f(xhat[i]) * lagrange_matrix[i]);
I'm getting confused with the FuncAnimation method. I was trying to show real-time sensor data on my raspberry pi using GPIOs. I set the x range to 100. When my data frames are over 100, I will only pick the recent 100 frames to show. At the beginning when the number of frames is less than 100, the pic shows correctly. The problem is that when frames are over 100, the later pic will overlap with the former pic and the graph just mess up. Here's the beginning graph and the overlap graph.
enter image description here
enter image description here
I checked the matplotlib API and I changed the param "blit" from True to False.
The overlap disappears but the frame rate is becoming too low.
Since I also used FuncAnimation with blit set True in another code and the overlap didn't appear, I guess there something else wrong.
The overlap code is below:
max_limit = 20
fig, ax = plt.subplots(light_num, 1)
data = []
lines = []
for i in range(light_num):
data.append([])
ln_one_light, = ax[i].plot([], [], 'r-')
lines.append(ln_one_light)
def init():
for i in range(light_num):
ax[i].set_xlim(0, max_limit)
ax[i].set_ylim(lower_bound, upper_bound)
return lines
def update(frame):
# print(frame)
global data
for i in range(light_num):
data[i].append(frame[i])
if len(data[i]) > max_limit:
data[i] = data[i][1:]
time_axis = np.arange(len(data[i]))
for i in range(light_num):
# print(time_axis, data[i])
lines[i].set_data(time_axis, data[i])
return lines
def gen_function():
res_array = []
output_string = ''
for i in range(light_num):
val = GPIO.input(light_io_array[i])
res_array.append(val)
output_string = output_string + str(val) + ' '
# print(res_array)
lights_data_writer.update_data(output_string)
yield res_array
ani = FuncAnimation(fig, update, frames=gen_function, interval = 500, repeat = True,
init_func=init, blit=True)
plt.show()
The code that I used with blit set as True, but no overlap happens:
fig, ax = plt.subplots(3, 1)
data_x, data_y, data_z = [], [], []
ln_x, = ax[0].plot([], [], 'r-')
ln_y, = ax[1].plot([], [], 'r-')
ln_z, = ax[2].plot([], [], 'r-')
def init():
for i in range(3):
ax[i].set_xlim(0, 100)
ax[i].set_ylim(-5, 5)
return (ln_x, ln_y, ln_z)
def update(frame):
(x, y, z) = frame
global data_x, data_y, data_z
data_x.append(x)
data_y.append(y)
data_z.append(z)
if len(data_x) > 100:
data_x = data_x[1:]
data_y = data_y[1:]
data_z = data_z[1:]
time_xyz = np.arange(len(data_x))
# print(time_xyz, data_x)
ln_x.set_data(time_xyz, data_x)
ln_y.set_data(time_xyz, data_y)
ln_z.set_data(time_xyz, data_z)
return (ln_x, ln_y, ln_z)
def gen_function():
while True:
(x, y, z) = adxl345.getAxes()
output_string = 'acc '+str(x)+' '+str(y)+' '+str(z)
imu_data_writer.update_data(output_string)
yield (x, y, z)
ani = FuncAnimation(fig, update, frames=gen_function, interval = 100,
init_func=init, blit=True)
plt.show()
Thank you for anyone who can have a look and check out what I have done wrong.
i am new to python. I am writing a data logging program and want to open a serial port, then read from it.
My problem is that calling this in my main():
# Handle serial
ser = serial.Serial(strPort, 9600)
doesnt allow me to invoke methods on the ser handle in other functions. Should i make a class or whats the best approach?
Here is the error message:
line 164, in updateData
line = ser.readline().rstrip()
NameError: name 'ser' is not defined
Here is the code:
# Uncomment the next two lines if you want to save the animation
import matplotlib
# matplotlib.use("Agg")
import sys
import serial
import argparse
import csv
import numpy
from matplotlib.pylab import *
from mpl_toolkits.axes_grid1 import host_subplot
import matplotlib.animation as animation
'''
ax03.legend([p031,p032], [p031.get_label(),p032.get_label()])
'''
def main():
# Sent for figure
font = {'size': 9}
matplotlib.rc('font', **font)
# Setup figure and subplots
f0 = figure(num=0, figsize=(12, 10)) # , dpi = 100)
f0.suptitle("Sensor Data", fontsize=12)
ax01 = subplot2grid((3, 2), (1, 0))
#ax02 = subplot2grid((4, 2), (1, 1))
ax02 = ax01.twinx()
ax03 = subplot2grid((3, 2), (0, 0), colspan=2, rowspan=1)
ax04 = subplot2grid((3, 2), (1, 1))
ax05 = subplot2grid((3, 2), (2, 0))
ax06 = subplot2grid((3, 2), (2, 1))
subplots_adjust(left=None, bottom=None, right=None,
top=None, wspace=0.3, hspace=0.3)
# Set titles of subplots
ax01.set_title('Heart Rate Quality and Sample Frequency')
ax03.set_title('Heart Rate')
ax04.set_title('Step Rate')
ax05.set_title('Perfusion Index')
ax06.set_title('Raw PPG')
# set y-limits
ax01.set_ylim(-1, 5)
ax02.set_ylim(100, 500)
ax03.set_ylim(30, 140)
ax04.set_ylim(-50, 250)
ax05.set_ylim(0, 500)
ax06.set_ylim(0, 50000)
# sex x-limits
ax01.set_xlim(0, 50.0)
# ax02.set_xlim(0,50.0)
ax03.set_xlim(0, 50.0)
ax04.set_xlim(0, 50.0)
ax05.set_xlim(0, 50.0)
ax06.set_xlim(0, 50.0)
# Turn on grids
ax01.grid(True)
# ax02.grid(True)
ax03.grid(True)
ax04.grid(True)
ax05.grid(True)
ax06.grid(True)
# set label names
ax01.set_xlabel("t[s]")
ax01.set_ylabel("HRQ")
ax02.set_xlabel("t[s]")
ax02.set_ylabel("samples[Hz]")
ax03.set_xlabel("t[s]")
ax03.set_ylabel("bpm")
ax04.set_xlabel("t[s]")
ax04.set_ylabel("Steps/min")
ax05.set_xlabel("t[s]")
ax05.set_ylabel("AC/DC ratio")
ax06.set_xlabel("t[s]")
ax06.set_ylabel("raw PS sample")
# Data Placeholders
t = zeros(0)
hr = zeros(0)
HRQ = zeros(0)
Fs = zeros(0)
stepRate = zeros(0)
ADCGain = zeros(0)
pI = zeros(0)
rawPPG = zeros(0)
ser = zeros(0)
# set plots
p011, = ax01.plot(t, HRQ, 'c-', label="HRQ", linewidth=2)
p021, = ax02.plot(t, ADCGain, 'r-', label="Sample Frequency", linewidth=2)
p031, = ax03.plot(t, hr, 'b-', label="Heart Rate", linewidth=2)
p041, = ax04.plot(t, stepRate, 'b-', label="Step Rate", linewidth=2)
p051, = ax05.plot(t, pI, 'y-', label="Perfusion Index", linewidth=2)
p061, = ax06.plot(t, rawPPG, 'g-', label="Raw PPG", linewidth=2)
# set lagends
ax01.legend([p011, p021], [p011.get_label(), p021.get_label()], loc=2)
#ax02.legend([p021], [p021.get_label()])
ax03.legend([p031], [p031.get_label()], loc=2)
ax04.legend([p041], [p041.get_label()], loc=2)
ax05.legend([p051], [p051.get_label()], loc=2)
ax06.legend([p061], [p061.get_label()], loc=2)
# Data Update
xmin = 0.0
xmax = 50.0
x = 0.0
# create parser
parser = argparse.ArgumentParser(description="LDR serial")
# add expected arguments
parser.add_argument('--port', dest='port', required=True)
# parse args
args = parser.parse_args()
#strPort = '/dev/tty.usbserial-A7006Yqh'
strPort = args.port
print('reading from serial port %s...' % strPort)
# Handle serial
ser = serial.Serial(strPort, 9600)
print('plotting data...')
# Logfile writer
# open('test.csv','w') as csvfile
#logwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
# interval: draw new frame every 'interval' ms
# frames: number of frames to draw
simulation = animation.FuncAnimation(
f0, updateData, blit=False, frames=1000, interval=100, repeat=True)
# Uncomment the next line if you want to save the animation
# simulation.save(filename='sim.mp4',fps=1,dpi=300)
plt.show()
def updateData(self):
global x
global t
global ser
global hr
global HRQ
global Fs
global ADCGain
global stepRate
global pI
global rawPPG
try:
line = ser.readline().rstrip()
data = [float(val) for val in line.split()]
# print data
print(data)
if(len(data) == 9):
# log data
for i in range(len(data)):
out_string = ""
out_string += str(data[i])
# logwriter.writerow(out_string)
# update variables
tmpT = data[0]
tmpFs = data[1]
tmpStepRate = data[2]
tmpHr = data[3]
tmpPI = data[4]
tmpHRQ = data[5]
tmpRawPPG = data[6]
except KeyboardInterrupt:
print('exiting')
hr = append(hr, tmpHr)
HRQ = append(HRQ, tmpHRQ)
Fs = append(Fs, tmpFs)
stepRate = append(stepRate, tmpStepRate)
pI = append(pI, tmpPI)
rawPPG = append(rawPPG, tmpRawPPG)
t = append(t, x)
x += 1
p011.set_data(t, HRQ)
p021.set_data(t, Fs)
p031.set_data(t, hr)
p041.set_data(t, stepRate)
p051.set_data(t, pI)
p061.set_data(t, rawPPG)
if x >= xmax - 10.00:
p011.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p021.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p031.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p041.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p051.axes.set_xlim(x - xmax + 10.0, x + 10.0)
p061.axes.set_xlim(x - xmax + 10.0, x + 10.0)
return p011, p021, p031, p041, p051, p061
# Call main
if __name__ == '__main__':
main()
I am doing some analysis on some simple data, and I am trying to plot auto-correlation and partial auto-correlation. Using these plots, I am trying to find the P and Q value to plot in my ARIMA model.
I can see on the graphs, but I am wondering if I can explicitly find, for each graph, where the plot crosses the axhline?
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
So in the above code, can I find, and show, where the lag_pacf plot crosses the axhlines that I have predetermined?
Thanks
You'll need to calculate the intersections between the line segments of lag_pacf and y's:
from matplotlib import pyplot as plt
import numpy as np
lag_pacf = np.random.randint(-10,10,30)
log_moving_average_difference = [i for i in range(30)]
#plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()
def line_intersection(line1, line2):
xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])
ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1]) #Typo was here
def det(a, b):
return a[0] * b[1] - a[1] * b[0]
div = det(xdiff, ydiff)
if div == 0:
return None
d = (det(*line1), det(*line2))
x = det(d, xdiff) / div
y = det(d, ydiff) / div
return x, y
def near(a, b, rtol=1e-5, atol=1e-8):
return abs(a - b) < (atol + rtol * abs(b))
def crosses(line1, line2):
"""
Return True if line segment line1 intersects line segment line2 and
line1 and line2 are not parallel.
"""
(x1,y1), (x2,y2) = line1
(u1,v1), (u2,v2) = line2
(a,b), (c,d) = (x2-x1, u1-u2), (y2-y1, v1-v2)
e, f = u1-x1, v1-y1
denom = float(a*d - b*c)
if near(denom, 0):
# parallel
return False
else:
t = (e*d - b*f)/denom
s = (a*f - e*c)/denom
# When 0<=t<=1 and 0<=s<=1 the point of intersection occurs within the
# line segments
return 0<=t<=1 and 0<=s<=1
plt.plot(lag_pacf)
plt.axhline(y=0, linestyle = '--', color = 'grey')
plt.axhline(y=-1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--',color = 'red')
plt.axhline(y=1.96/np.sqrt(len(log_moving_average_difference)),linestyle = '--', color = 'green')
plt.title('Partial Autocorelation Function')
yys = [0,-1.96/np.sqrt(len(log_moving_average_difference)),1.96/np.sqrt(len(log_moving_average_difference))]
xx, yy = [],[]
xo,yo = [k for k in range(30)],lag_pacf
d = 20
for i in range(1,len(lag_pacf)):
for k in yys:
p1 = np.array([xo[i-1],yo[i-1]],dtype='float')
p2 = np.array([xo[i],yo[i]],dtype='float')
k1 = np.array([xo[i-1],k],dtype='float')
k2 = np.array([xo[i],k],dtype='float')
if crosses((p2,p1),(k1,k2)):
seg = line_intersection((p2,p1),(k1,k2))
if seg is not None:
xx.append(seg[0])
yy.append(seg[1]-d)
plt.scatter(seg[0],seg[1],c='red')
plt.xlim(0,30)
plt.ylim(-10,10)
plt.show()
, for this completely randomized example:
I obtained this:
I want to show the elapsed time in my animation in matplotlib. I created a text instance, but when I am trying to update it(based on the frame number) nothing changes. Here is part of the code:
fig = plt.figure()
ax = plt.axes(xlim =(-4E8,4E8), ylim= (-4E8,4E8))
time_text = ax.text(0.05, 0.95,'',horizontalalignment='left',verticalalignment='top', transform=ax.transAxes)
def init():
for line, pt in zip(lines, pts):
line.set_data([], [])
pt.set_data([], [])
time_text.set_text('hello')
return lines + pts
return time_text
def animate(i):
i = (10 * i) % data.shape[1]
#update lines and points here
for line, pt, dt in zip(lines,pts, data):
x, y, z = dt[:i].T
line.set_data(x, y)
pt.set_data(x[-1:], y[-1:])
time_text.set_text('time = %.1d' % i) #<<<<<Here. This doesn't work
return lines + pts
return time_text
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=700, interval=1, blit=True)
plt.show()
The time depend on the frame number so I tried this:
time_text.set_text('time = %.1d' % i)
but it doesn't get updated(stays "hello").
Any ideas? What am I doing wrong?
Change this:
return lines + pts
return time_text
to this:
return lines + pts + [time_txt,]
The second return is never getting hit, so it doesn't know to update that artist.