2013-02-21 73 views
6

有没有方法根据文本文件中的值绘制函数?直接从文本文件绘制函数

我知道如何在gnuplot中定义一个函数,然后绘制它,但这不是我所需要的。 我有一个定期更新函数的常量表。当这个更新发生时,我希望能够运行一个用这条新曲线绘制图形的脚本。由于有很少的数字可以画出,所以我想让程序自动化。

下面是一个例子表常数:

location a b c 
1  1 3 4 
2 

有两种方法我看到解决这个问题,但我不知道是否以及如何实施。

  1. 然后我就可以用awk生成字符串:f(x)=1(x)**2+3(x)+4,写入到一个文件,并以某种方式使gnuplot的阅读一定x范围这个新文件和情节。
  2. 或者在gnuplot里面使用awk,比如f(x) = awk /1/ {print "f(x)="$2等,或者直接在plot命令中使用awk。

我的任何情况下,我卡住了,并没有找到这个问题的解决方案在线,你有什么建议吗?

+0

您为什么在寻找单线解决方案? – mgilson 2013-02-21 17:31:41

+0

当我使用'gnuplot'时,我总是从'Perl'中调用它。如果这不是一个选项,我会建议从'gnuplot'脚本内部调用'awk'。见[这里](http://stackoverflow.com/questions/12846717/using-awk-or-other-shell-command-inside-gnuplot-function)和[here](http://security.riit.tsinghua。 edu.cn/~bhyang/ref/gnuplot/datafile3-e.html)来实现这个目标。 – Steve 2013-02-21 23:49:51

回答

0
awk '/1/ {print "plot "$2"*x**2+"$3"*x+"$4}' | gnuplot -persist 

会选择线路,并绘制它

1

这个问题(gnuplot store one number from data file into variable)对我有一些提示的第一个答案。

在我的情况下,我有一个包含抛物线参数的文件。我已经将参数保存在gnuplot变量中。然后我绘制每个时间步包含参数变量的函数。

#!/usr/bin/gnuplot 

datafile = "parabola.txt" 

set terminal pngcairo size 1000,500 
set xrange [-100:100] 
set yrange [-100:100] 
titletext(timepar, apar, cpar) = sprintf("In timestep %d we have parameter a = %f, parameter c = %f", timepar, apar, cpar) 

do for [step=1:400] { 
    set output sprintf("parabola%04d.png", step) 

    # read parameters from file, where the first line is the header, thus the +1 
    a=system("awk '{ if (NR == " . step . "+1) printf \"%f\", $1}' " . datafile) 
    c=system("awk '{ if (NR == " . step . "+1) printf \"%f\", $2}' " . datafile) 

    # convert parameters to numeric format 
    a=a+0. 
    c=c+0. 

    set title titletext(step, a, c) 

    plot c+a*x**2 
} 

这给出了一个系列叫parabola0001.png, parabola0002.png PNG文件, parabola0003.png, ...,分别表示从被称为parabola.txt文件中读取参数抛物线。标题包含给定时间步的参数。

对于了解你要知道的是,gnuplot的system()功能:

  • 双引号里面的东西不被gnuplot的
  • 点解析是在gnuplot的连接字符串
  • 为双引号AWK printf命令已经被越狱,从gnuplot的解析器隐藏

为了测试这个gnuplot的脚本,保存成任意名称的文件,例如parabolaplot.gplot并使其可执行(chmad a+x parabolaplot.gplot)。该parabola.txt文件可以用

awk 'BEGIN {for (i=1; i<=1000; i++) printf "%f\t%f\n", i/200, i/100}' > parabola.txt

3

另一个possibilty创建有这个有点通用版本,你可以做到以下几点:

假设,参数都存储在一个文件parameters.dat与第一包含变量名和所有其他的参数集,像

location a b c 
1  1 3 4 

脚本文件行看起来是这样的:

file = 'parameters.dat' 
par_names = system('head -1 '.file) 
par_cnt = words(par_names) 

# which parameter set to choose 
par_line_num = 2 
# select the respective string 
par_line = system(sprintf('head -%d ', par_line_num).file.' | tail -1') 
par_string = '' 
do for [i=1:par_cnt] { 
    eval(word(par_names, i).' = '.word(par_line, i)) 
} 
f(x) = a*x**2 + b*x + c 

plot f(x) title sprintf('location = %d', location)