使用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上的秒表测试了它
以下是我对此问题的疑问:
祝你好运
**编辑:任何提示或建议将不胜感激。非常感谢:)