通过Python将文件输入gnuplot

2 投票
1 回答
1901 浏览
提问于 2025-04-16 17:28

我正在尝试用gnuplot和gnuplot.py从MySQL数据库中提取一些数据并绘制图表。我从MySQL数据库中读取最新的10行数据,并把它们存储在一个临时文件中,这个文件是要被gnuplot读取的。我可以通过终端手动设置来完成这个操作,但我就是不知道如何通过Python把这个文件加载到gnuplot中。如果你能给我一个更简单的方法,或者告诉我怎么做,我会非常感激。

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]是x轴的数据,row[1]是y轴的数据。

1 个回答

2

这个不行,因为在你用write写入文件后,文件的光标会停在文件的最后。如果你真的想这么做(其实不写数据到文件会更好),你需要把光标移动回文件的开头:

datafile.seek(0)

现在你可以从文件的开头用read()读取内容了。

撰写回答