Matplotlib轴格式化

时间:2012-08-15 16:36:05

标签: python plot matplotlib

我想将当前日期和时间添加到实时图的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_())

1 个答案:

答案 0 :(得分:1)

您可以先查看一个简单示例,了解如何使日期标记有效:http://matplotlib.sourceforge.net/examples/pylab_examples/finance_demo.html

首先,您需要导入日期绘图类,例如:

from matplotlib.dates import DateFormatter, WeekdayLocator, MONDAY

文档位于http://matplotlib.sourceforge.net/api/dates_api.html

然后在图的定义中,设置定位器(用于刻度线)和格式化器(用于刻度标签)。下面的代码在每个星期一设置刻度线:

    self.ax.xaxis.set_major_locator(WeekdayLocator(MONDAY))
    self.ax.xaxis.set_major_formatter(DateFormatter('%b %d'))
    self.ax.xaxis_date()

现在应该将datetime.datetime用于X轴值和范围而不是整数。我希望MySQLdb返回datetime.datetime个对象,否则你将不得不转换时间戳。

如果您尝试绘制空图表,日期格式化程序会抱怨。不要忘记设置合理的初始限制。

以下是您的代码示例,其中我删除了数据库代码(以及更多代码)并将其替换为生成的值:

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_())