使用pyplot

时间:2016-04-19 08:15:27

标签: python mysql matplotlib graph real-time

使用pyplot

在实时图表上绘制mysql数据

大家好,感谢提前阅读。 我一直在研究一个Mysql数据库,每隔几秒就从传感器中添加一个样本,并且每个都创建一个表,这样所有的表都不会变得非常庞大。我已经这样做了, 我想知道的是绘制数据库中最近15个最近的样本,总是最后15个,我使用此查询来提取数据 来自Mysql:

“从TableName中选择ColumnName其中ID>((从TableName中选择max(ID)) - (15 + 1))按ID asc排序;”

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb, time, locale, datetime, pyoo, random, os.path, matplotlib
from matplotlib import pyplot as plt
from itertools import chain
from subprocess import Popen
import RPi.GPIO as GPIO
import mysql.connector as My
import numpy as np

locale.setlocale(locale.LC_ALL, '')

def Informacion():
        info_dato = round(random.uniform(1,5),2)
        info_dia = time.strftime('%A')
        info_fecha_hora = time.strftime('%Y-%m-%d %H:%M:%S')
        info_lugar = 'CD python'
        return info_dato, info_dia, info_fecha_hora, info_lugar

def Tiempo():
        tiempo_justo_ahora = datetime.datetime.now()
        tiempo_dia = tiempo_justo_ahora.strftime('%A')
        tiempo_fecha = tiempo_justo_ahora.strftime('%x')
        tiempo_hora_actual = tiempo_justo_ahora.strftime('%X')
        tiempo_hoy = tiempo_justo_ahora
        while (tiempo_hoy.isoweekday() > 1):
               tiempo_hoy = tiempo_hoy - (datetime.timedelta(days = 1))
        tiempo_iso = tiempo_hoy.isocalendar()
        tiempo_fecha_inicio = tiempo_hoy.strftime('%x')
        tiempo_fecha_fin = (tiempo_hoy + datetime.timedelta(days=6)).strftime('%x')
        time.sleep(0.1)
        return tiempo_dia, tiempo_fecha, tiempo_hora_actual, tiempo_iso[0], tiempo_iso[1], tiempo_fecha_inicio, tiempo_fecha_fin

x = Tiempo()
chequeo = 'El programa fue ejecutado el dia %s %s a las %s' % (x[0],x[1], x[2])
print chequeo
#This is actually just to know when the program was executed, it prints
# "The program was execute the day %(day in letters)s %(date)s %(time)s

Parametros = {
'user': 'XXXX',
'password': 'XXXX',
'host': 'localhost',
'database': 'XXXX',
'raise_on_warnings': True,
'collation': 'utf8_spanish2_ci',}

idioma = "set lc_time_names = 'es_PA';"
tabla = "semana_%s_del_%s" % (x[4], x[3])
crear_tabla = ("create table %s (num_muestra int auto_increment not null,"
            "valor float not null, dia char(10) not null, fecha_hora datetime not null, "
            "punto_muestra char(10) not null, primary key (num_muestra)) character set utf8 collate utf8_spanish2_ci;")
insertar_dato = ("insert into %s (valor, dia, fecha_hora, punto_muestra) values"
            "(%f, '%s', str_to_date('%s','%%Y-%%m-%%d %%H:%%i:%%s'), '%s')")
existe_tabla = "select count(*) from information_schema.tables where table_schema = 'prueba1' and table_name = '%s';"
buscar_datos = "select %s from %s;"
datos_grafica = ("select %s from %s where num_muestra > " 
            "((select max(num_muestra) from %s) - %d) order by num_muestra asc;")

#...Functions to query...too long, tough if needed please let me know :)

def Formatos_grafica (fig_subplot):
       plt.cla()
       fig_subplot.patch.set_facecolor('lightgrey')
       fig_subplot.xaxis.set_major_formatter(formato_fecha)
       fig_subplot.set_title('Prueba 1')
       fig_subplot.set_xlabel('Tiempo')
       fig_subplot.set_ylabel('Valor')
       fig_subplot.grid(True)

formato_fecha = matplotlib.dates.DateFormatter('%A\n%H:%M:%S')
plt.ion()
figura = plt.figure()
ax = figura.add_subplot(111)
Formatos_grafica(ax)
plt.show(block = False)

try:
      #Checking if the database exist, otherwise create it...
      #...Adding the value from the Informacion() function to the database..

      #...Graph part
      ti = Extraer_datos(datos_grafica % ('fecha_hora', tabla, tabla, 16))
      tiempos = matplotlib.dates.date2num(ti)
      valores = Extraer_datos(datos_grafica % ('valor', tabla, tabla, 16))
      Formatos_grafica(ax)
      ax.plot(tiempos, valores)
      ax.scatter(tiempos, valores, color = 'green')
      figura.canvas.draw()
      time.sleep(5)

except KeyboardInterrupt:

      print('\n Se ha ejecutado la salida manual del programa (Control + C)')
      plt.cla()
      plt.clf()
      plt.close()

except Exception as e:

      print('Ha ocurrido un error inesperado \n')
      print(e)
      plt.cla()
      plt.clf()
      plt.close()

我从我所制作的代码中获得的是我想要的,一个最后15个的情节(尽管有时候我认为16个因为某些未知原因给我, 并不是真的很烦,但它有点奇怪)但是每个图表的时间大约为9到12秒(从时间上增加5秒.sleep(5) 功能也大约0.5,因为我用我的手机jaja上的秒表测试了它

以下是我对此问题的疑问:

  1. 我是否以糟糕的方式使用matplotlib pyplot功能?
  2. 对于我擦除轴并在绘图前再次格式化的功能,这是因为我没有这样做的时间, 我在图表上有一个错误,每次在同一轴上出现一个新的图(不同的图有不同的图 颜色,这就是我注意到的)。有没有办法改变这个?
  3. 在循环之前,我总是收到警告说:“未来警告:元素比较失败;返回标量,但是 将来会进行元素比较 如果self._edgecolors == str('face'):“,这是我应该担心的事情,或者是因为我到目前为止搜索的一个错误, 大多数时候这个警告都是因为一个错误而发生的。
  4. 如果有办法使用matplotlib更快地实时绘图?我一直在阅读关于动画的内容,但我不确定它是否真的值得,或者它会在每个样本的同一时间进行图形化。
  5. 我正在使用plt.ion()来激活交互模式,但我听说如果你想使用像修补程序这样的界面你就不需要了 (我计划在正确绘制样本后制作和使用)。这是真的吗?
  6. 我很难不总是从数据库中查询15个最新的样本,只需要在循环之前执行一次,然后将其存储在列表中,然后每当我得到一个新样本时,我添加iit到列表并从列表中删除1。有办法吗?
  7. 祝你好运

    **编辑:任何提示或建议将不胜感激。非常感谢:)

0 个答案:

没有答案