matplotlib.animation绘制在循环内部

时间:2017-06-21 13:28:04

标签: python matplotlib

我通过三个传感器节点的套接字连接向我提供数据,每个子图有三个子图,分别用于温度,电压和湿度值。临时子图应绘制每个节点的温度值。同样适用于湿度和电压。这是我写的代码:

import socket
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pickle


fig = plt.figure()
temp_plot = fig.add_subplot(3,1,1)
volt_plot = fig.add_subplot(3,1,2)
pres_plot = fig.add_subplot(3,1,3)


maclist=['xyz01','xyz02','xyz03']
temp=[]
volt=[]
time=[]
pres=[]


ip = 'server IP address'

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((ip,10030))
print 'connection established to server...'

def animate(i):
  global sock  
  info = sock.recv(1024)
  info = pickle.loads(info)

  ind = maclist.index(info['MAC'])
  if len(temp[ind]) == 10: #to make sure every time 10 points are plotted
   temp[ind].pop(0)
   time[ind].pop(0)
   volt[ind].pop(0)
   pres[ind].pop(0)

  temp[ind].append(info['TEMP'])
  time[ind].append(info['TIME'])
  volt[ind].append(info['VOLT'])
  pres[ind].append(info['PRES'])
  temp_plot.clear()
  volt_plot.clear()
  pres_plot.clear()

  for i in range(len(maclist)):
    temp_plot(time[i],temp[i])
    volt_plot(time[i],volt[i])
    pres_plot(time[i],pres[i])

if __name__ == '__main__' :
   ani = animation.FuncAnimation(fig,animate,interval = 100)
   plt.show()
  

info =   { 'MAC': 'xyz01', 'TIME':21.4131, 'TEMP':27.0, 'VOLT':2.5, 'PRES':892}

temp,volt,time和pres是包含子列表的列表, 因为ex-temp [0]包含来自node0的温度值列表。

这段代码给了我一个错误,我怀疑是因为试图在循环中绘图

  

“temp_plot(时间[I],温度[I])
  TypeError:'AxesSubplot'对象不是   可骂'

任何人都可以帮助我这个

1 个答案:

答案 0 :(得分:0)

temp_plot是您要绘制的子图。你不能自己调用​​子图。就像你不写plt(x,y)ax(x,y),而是写plt.plot(x,y)ax.plot(x,y)一样;在这里你需要

temp_plot.plot(time[i],temp[i])
volt_plot.plot(time[i],volt[i])
pres_plot.plot(time[i],pres[i])