使用 PyGnuplot 结束 gnuplot 过程

问题描述 投票:0回答:4

我使用 gnuplot(通过 Python 和 PyGnuplot)作为来自 Arduino 的数字数据的实时绘图仪。此外,我想在任意点保存情节。每当我尝试在实时绘图时从 gnuplot 保存 pdf/jpg 时,gnuplot 就会出现。

我认为在将绘图保存为 pdf 之前有必要重新启动 gnuplot 进程 - 使用 PyGnuplot.c('quit') 或类似命令根本无法工作。当我使用不同的 python 脚本进行实时绘图和保存 pdf 时,一切正常,但我知道没有必要运行两个脚本。

这是一个正在运行(分别未运行)的最小示例:

import random,time
import PyGnuplot as gp
filename = "data.txt"

def rand():
    return random.random()

def writetxt(file,info):
    fobj = open(file, "a")
    fobj.write(info)
    fobj.close()

def liveplot(file):
    gp.c('plot "' + file + '" with lines')

def plotinfile(dat):
    gp.c('set terminal pdf')
    gp.c('set output "example.pdf"')
    gp.c('plot "' + dat + '" with lines')
    gp.c('unset output')
    gp.c('set terminal x11')

for i in range(10): 
         onerow = str(i) + " " + str(rand()) + " " + str(rand()) #simulate incoming data
         print(onerow) #print in console for comparison
         writetxt(filename ,onerow + "\n") #write data into txt-file
         liveplot(filename) #liveplot the data from txt-file
         if i == 4: #simulate an arbitrary point for saving
            plotinfile(filename) #save graph from txt-file to pdf
         time.sleep(1)   #incoming data occurs only every second
python gnuplot
4个回答
0
投票

我相信您想在绘图中添加曲线或添加数据点,并间歇性保存。如果是这样,这样的事情就足够了:

python
>>> import PyGnuplot as gp
>>> gp.c('plot sin(x)')
>>> gp.pdf('sin_graph.pdf')   # discretionary save point 1 
>>> gp.c('replot cos(x)')     # add a new curve  
>>> gp.pdf('sin_and_cos_graph.pdf') # discretionary save point 2

如果您只有 pdfcario 终端而不是 pdf,那么您需要通过自己编写 pdf 来解决 pygnuplot c.pdf 脚本:

>>>filename = 'sin_graph.pdf'
>>>gp.c('set term pdf enhanced size 14cm, 9cm color solid')
>>>gp.c('set out "' + filename + '";')
>>>gp.c('replot;')
>>>term='x11`  # or whatever term you typically use
>>>gp.c('set term ' + str(term) + '; replot')

您可以将此例程包装到一个函数中,并以

filename
terminal
作为参数。无论如何,每次您想要打印 pdf 时都必须执行这一系列命令。


0
投票

gnuplot 不会关闭输出文件,直到 (1) 终端类型更改为其他类型或 (2) 存在显式命令“unset output”。否则,gnuplot 会等待查看是否有另一个绘图命令将进入同一个输出文件。


0
投票

问题是:所使用的终端不在手边。使用另一个终端解决了该问题。感谢您的帮助。在 PyGnuplot 中使用终端 x11 - 这对我来说不可用(我仍然不知道为什么,不知道如何安装它,并且仍然不知道如何使用 PyGnuplot 结束 gnuplot 进程...)


0
投票

您面临的问题(Gnuplot 有时无法正确关闭)已通过 PyGnuplot 版本 0.12.3 的最新更新得到解决。这个新版本提供了一个功能,允许您创建多个图形实例并分别关闭它们,这应该正确结束 Gnuplot 进程。

此外,它还支持使用 Gnuplot 的特殊拟合算法,这可能对您的用例有益。

PyGnuplot 的使用略有变化。现在,您从 PyGnuplot 导入“gp”类来创建新图形。以下是如何执行此操作的示例:

from PyGnuplot import gp
fig1 = gp()
fig1.a('plot sin(x)')

fig1.quit()  # This will terminate the gnuplot instance associated with this figure

使用上面的代码,您可以创建多个Gnuplot实例并根据需要终止它们。这应该有助于解决您在实时绘图时尝试将绘图另存为 PDF 时遇到的问题。

此外,通过新的更新,数据将直接传递到 Gnuplot,而不是将其保存到“tmp.dat”文件中。如果你想恢复到以前的行为(在我的带有 ram 磁盘的 Linux 系统上运行得更快),你可以使用以下代码来实现:

gp.save(data, filename='tmp.dat')
gp.c('plot "tmp.dat"')

这应该通过启用实时绘图和保存绘图的单独处理来解决您当前的问题。您不再需要为这些任务运行两个单独的脚本。

有关此信息的来源,请参阅 Gnuplot 0.12.3 发行说明

© www.soinside.com 2019 - 2024. All rights reserved.