Reputation:
I want to add the current date and time to the x-axes of a real time plot. I have tried almost everything beginning with custom ticks to custom axes, but I cannot seem to add it. How should I do this?
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_())
Upvotes: 0
Views: 900
Reputation:
You can check a simple example first to get an idea of how to make date markers work: http://matplotlib.sourceforge.net/examples/pylab_examples/finance_demo.html
First you will need to import the date plotting classes, for example:
from matplotlib.dates import DateFormatter, WeekdayLocator, MONDAY
The documentation is available at http://matplotlib.sourceforge.net/api/dates_api.html
Then in the definition of the figure, set the locator (for tick marks), and formatter (for tick labels). The code below sets tick marks on every monday:
self.ax.xaxis.set_major_locator(WeekdayLocator(MONDAY))
self.ax.xaxis.set_major_formatter(DateFormatter('%b %d'))
self.ax.xaxis_date()
You should use datetime.datetime
now for X-axis values and ranges instead of integers. I expect MySQLdb to return datetime.datetime
objects, otherwise you will have to convert the timestamps.
The date formatter will complain if you try to plot an empty graph. Don't forget to set reasonable initial limits.
Here is an example of your code, where I stripped the database code (and some more) and replaced it with generated values:
import sys
from pylab import *
from PyQt4 import QtGui
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.dates import DateFormatter, WeekdayLocator, MONDAY
import datetime
import random
class CPUMonitor(FigureCanvas):
def __init__(self):
# Dummy variable to simulate time.
self.delay = 0
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.xaxis.set_major_locator(WeekdayLocator(MONDAY))
self.ax.xaxis.set_major_formatter(DateFormatter('%b %d'))
self.ax.xaxis_date()
# Set resonable initial limits.
td = datetime.timedelta(1)
self.ax.set_xlim(datetime.datetime.now(), datetime.datetime.now() + td)
self.dates = []
self.user =[]
self.l_user, = self.ax.plot([],self.user, label='Total %')
self.ax.legend()
self.timer = self.startTimer(5000)
def get_database_data(self):
self.delay += 1
td = datetime.timedelta(0, self.delay * 5)
return [random.random(), datetime.datetime.now() + td]
def prepare_cpu_usage(self):
t = self.get_database_data()
return [t[0],t[1]]
def get_cpu_usage(self):
return self.prepare_cpu_usage()
def timerEvent(self, evt):
result = self.get_cpu_usage()
self.user.append(result[0])
self.dates.append(result[1])
self.l_user.set_data(self.dates, self.user)
if len(self.dates) >= 2:
self.ax.set_xlim(self.dates[0], self.dates[-1])
self.draw()
app = QtGui.QApplication(sys.argv)
widget = CPUMonitor()
widget.setWindowTitle("Pong: CPU Usage")
widget.show()
sys.exit(app.exec_())
Upvotes: 1