开发者

File input to gnuplot through python

开发者 https://www.devze.com 2023-03-05 00:15 出处:网络
I am trying to draw a graph of some data I pull out of a MySQL database through python with gnuplot and gnuplot.py.

I am trying to draw a graph of some data I pull out of a MySQL database through python with gnuplot and gnuplot.py. I read the latest 10 lines of data from the MySQL database and store them in a temp file which is supposed to be read by gnuplot. I can 开发者_如何学JAVAdo this the manual way by setting through the terminal, but I simply can't see how I should load the file into gnuplot through python. If you can show me an easier way to do this, or simply a way to do it at all, I would be very grateful.

import MySQLdb
import Gnuplot

datafile = open('data', 'w+r')

gp = Gnuplot.Gnuplot(persist=1)
gp('set style data lines')
gp('set term png')
gp('set output "escan_graph.png"')
gp('set datafile separator "|"')

db = MySQLdb.connect(host="localhost", user="root", passwd="password", db="zig")
cursor = db.cursor()

cursor.execute("select * from escan_data")

numrows = int(cursor.rowcount) #get the count of total
# get and display one row at a time

if numrows > 10:
        start = numrows-10
else:
        start = 0

for x in range(start,numrows):
        row = cursor.fetchone()
        print row[0], row[1]
        datafile.write(str(row[0]) + "|" + str(row[1]) + "\n")



databuff = Gnuplot.Data(datafile.read(), title="test")


gp.plot(databuff)

row[0] is the x-axis and row[1] is y-axis.


This doesn't work because after you write the file object's cursor is at the end of the file. If you want to really do this (you are better off not writing the data to a file at all), you need to move the cursor back to the beginning of the file:

datafile.seek(0)

Now you can read() from the beginning of the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号