2011年6月23日

[心得]gnuplot in action -- chapter 12

12章介紹了gnuplot的macro還有呼叫其他程式跟被其他程式呼叫
gnuplot 4.2開始支援string variable,也就是可以被解釋為'string',比方說
file_name='data1.txt'
plot file_name title file_name  #對比 plot 'data1.txt' title 'data1.txt'
又或者以類是函數的方式
file_name(prefix)=prefix.'.txt'
plot file_name('data1')
其中file_name就是被取代成字串(有附帶引號喔),但是如果不是字串的部分,比方如using 1:2就要使用macro,macro會被解釋為命令的一部份
set macro
cols = 'using 1:3'
style= 'with linespoints 3"
plot 'data1.txt' @cols @styles
使用@這個符號就可以呼叫macro但是字串裡面呼叫macro是行不通的,比方
file_name='data1'
plot '@file_name.txt'
書中也給出了一個不錯的例子,如果要使用一個function來產生一段指令來執行可以
export(file)=sprintf("set t push;set t png; set o '%s';replot set o; set t pop",file);
呼叫的方式
set macro
cmd=export('out.png')
@cmd

在gnuplot裡面呼叫shell command使用system這個指令
system "ls"
system "lpr -P laser plot.ps"
如果要取得執行結果就直接assign給字串變數
now=system("date")
如果log file是由時間順序編碼,可以用這樣子取得
其實我覺得由shell script來接手這一段或許是個不錯的選擇,接著就是由其他程式語言來呼叫gnuplot產生圖形,這是個不錯的idea(自我認為XD)

我特別喜歡python,所以這邊只寫有關python的部分,其實書中還有shell script或者perl的呼叫方式,shell大家應該很熟,perl我不喜歡:P
import os
import math
gp=os.popen('/usr/bin/gnuplot', 'w')
gp.write("set output 'graph.png'; set term png;")
gp.write("plot '-u' u 1:2 w lines, '-' u 1:2 w lines\n")
x=-5.0
while (x<=5.0):
  gp.write("%f %f\n" %(x,math.sin(x))
  x+=0.5
gp.write("e\n")
gp.close()
書中也提醒,其實很常常忘記加上\n這個換行符號導致錯誤,這個錯誤不容易發覺,且每次所有設定都要由程式設定一次。我覺得可以把常用的設定寫入某個xxx.plt,然後透過call放進來,再把動態資料產生或者其他動態的部分用python去填補。其實我覺得產生的資料應該由python輸出到檔案,一來可以保留log,二來在輸入很方便,不是每次計算(除非每次資料都不一樣),由python呼叫的好處是,可以直接在一種程式語言內完成所有工作

另外此章節還有提到一些gnuplot的環境變數,比方說GNUTERM、GNUPLOT_FONTPATH...等等,請自行參考書本或網路資料吧。

最後作者demo了如何結合gnuplot繪製一些圖形,直接透過cgi的方式放到網頁上,其實我認為大多數的web script language都有GD function,可以透過這些GD function,繪製一些圖形應改也是輕鬆寫意啦,gnuplot是提供了另外一種選擇

沒有留言: