2011/07/13

python tips: create line graph with matplotlib

*** sample code (mypg.py) ***
#/usr/bin/env python                                                       
# coding:utf-8

# need to install python-pygresql
import pg
import sys
from pylab import *

def main():
argvs = sys.argv
argc = len(argvs)

# check argument
if (argc != 4):
print "Usage: python %s dbname dbuser dbpass" % (argvs[0])
sys.exit(1)

dbname=argvs[1]
dbuser=argvs[2]
dbpass=argvs[3]
dbobj = getConnection(dbname, dbuser, dbpass)

# input data from database tables
Lx = getValueX()
L1 = collectData(dbobj, '1')
L2 = collectData(dbobj, '2')
L3 = collectData(dbobj, '3')
L4 = collectData(dbobj, '4')

# plot data using matplotlib
plot(Lx, L1, label='id=1')
plot(Lx, L2, label='id=2')
plot(Lx, L3, label='id=3')
plot(Lx, L4, label='id=4')

# set labels and title
xlabel('hour')
ylabel('random_value')
title('plot test')

# draw legend
legend()

# draw graph
show()

dbobj.close()

def getValueX():
L = []
hour = 0
while (hour <= 23):
L.append(hour)
hour += 1
return L

# collecting data if same id
def collectData(dbobj, target):
L = []
sn = 0
while sn <= 23:
dbtable='public.table_' + str(sn)

sql="SELECT * FROM %s WHERE id = '%s';" % (dbtable, target)
for row in dbobj.query(sql).dictresult():
if row['id'] == target:
L.append(int(row['value']))
sn += 1

return L
# debug function
def showTables(dbobj):
for tbl in dbobj.get_tables():
print tbl

# initialize db connection
def getConnection(dbname, dbuser, dbpass):
pg.set_defhost('localhost')
pg.set_defport(5432)
pg.set_defbase(dbname)
return pg.DB(user=dbuser, passwd=dbpass)

if __name__ == "__main__":
main()


*** output from above code ***
yaboo@maniac:~/$ python mypg.py mydb test test



*** matplotlib reference pages ***
ぐうたらの部屋
Matplotlib サンプル集 - Kaiseki
http://www.ike-dyn.ritsumei.ac.jp/~uchida/scipy-lecture-notes/intro/index.html

No comments:

Post a Comment

100