我想将当前日期和时间添加到实时图的 x 轴上。我已经尝试了几乎所有从自定义刻度到自定义轴的东西,但我似乎无法添加它。我该怎么做?
import sys
import pylab
from pylab import *
from PyQt4 import QtGui,QtCore
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg \
import FigureCanvasQTAgg as FigureCanvas
import MySQLdb as mdb
class CPUMonitor(FigureCanvas):
def __init__(self):
self.date = []
conn = mdb.connect("serv","user","pass","db")
self.cur = conn.cursor()
self.before = self.prepare_cpu_usage()
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
FigureCanvas.__init__(self, self.fig)
self.ax.set_title("Pong | CPU Utilization")
self.ax.set_xlabel("Datetime")
self.ax.set_ylabel("CPU %")
self.ax.set_autoscale_on(False)
self.user =[]
self.l_user, = self.ax.plot([],self.user, label='Total %')
self.ax.legend()
self.fig.canvas.draw()
self.cnt = 0
self.timerEvent(None)
self.timer1 = QtCore.QTimer()
self.timer1.timeout.connect(self.get_database_data)
self.timer1.start(5)
self.timer = self.startTimer(5000)
def get_database_data(self):
self.cur.execute("SELECT cpu,date FROM status WHERE date = (SELECT MAX(date) FROM status);")
self.data_db = self.cur.fetchone()
return self.data_db
def prepare_cpu_usage(self):
t = self.get_database_data()
return [t[0],t[1]]
def get_cpu_usage(self):
now = self.prepare_cpu_usage()
self.before = now
print self.before
return self.before
def datetime(self):
self.dates = self.get_cpu_usage()
self.dates = self.dates[1]
self.date.append(self.dates)
return str(self.dates)
def timerEvent(self, evt):
result = self.get_cpu_usage()
self.user.append(result[0])
self.l_user.set_data(range(len(self.user)), self.user)
self.fig.canvas.draw()
CurrentXAxis=pylab.arange(len(self.user)-1000,len(self.user),1)
self.ax.axis([CurrentXAxis.min(),CurrentXAxis.max(),0,100])
self.cnt += 1
app = QtGui.QApplication(sys.argv)
widget = CPUMonitor()
widget.setWindowTitle("Pong: CPU Usage")
widget.show()
sys.exit(app.exec_())