2013-02-21 76 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)