要畫一張能放進論文裡的圖,不一定得動用龐大的數學軟體。Gnuplot 體積小、跨平台、指令乾脆,還能直接輸出 LaTeX 語法,是寫科學文件時非常順手的一把刀。以下從安裝開始,一路做實驗到能上得了印刷體的成品圖。
Gnuplot 在 Linux 與 Windows 上都有版本,安裝方式各自說明。
一行指令解決,系統會自動處理相依性:
# apt-get install gnuplot
安裝完在命令列輸入:
$ gnuplot
出現 gnuplot> 提示符就進來了。這個提示符就是 Gnuplot 自己的 shell,所有指令都在這裡輸入。
到 https://www.sourceforge.net 搜尋 gnuplot,下載 win32 的 zip 包,解壓到本機目錄(假設是 c:\gnuplot),進入 bin 資料夾雙擊 wgnuplot.exe,就會開啟圖形介面的 Gnuplot。
在提示符下輸入:
gnuplot> plot [-3.14:3.14] sin(x)
馬上就能看到結果:橫軸、縱軸、圖例都齊了。別看它個頭小,功能一點不含糊。如果不想要圖例:
gnuplot> unset key
要還原:
gnuplot> set key default
再重跑一次繪圖指令,圖例就會依你的設定出現或消失。
Gnuplot 通常用於科學繪圖,而優秀的科技文獻多半以 LaTeX 寫成,所以它提供了直接輸出 tex 的能力,只要把 output 設成 latex:
gnuplot> set terminal latex
gnuplot> set output "sin.tex"
gnuplot> plot [-3.14:3.14] sin(x)
這時會產生一個 sin.tex,裡頭全是繪圖指令,用記事本打開看得一清二楚,看不懂也沒關係,忽略即可。在你的文件裡這樣引用:
\begin{figure}
\begin{center}
\input{sin.tex}
\end{center}
\end{figure}
編譯成 PDF 之後,圖就老實待在文章裡了。以後凡是要放進 LaTeX 的圖,都能用這招。
素圖能用,但稍嫌單調,論文裡的圖通常需要軸標籤與說明:
gnuplot> set terminal latex
gnuplot> set output "sinagain.tex"
gnuplot> set size 5/5.,4/3.
gnuplot> set format xy "$%g$"
gnuplot> set title "This is a plot of $y=\\sin(x)$"
gnuplot> set xlabel "This is the $x$ axis"
gnuplot> set ylabel "This is the $y$ axis"
gnuplot> plot [0:6.28] [0:1] sin(x)
一樣生成 tex 檔、一樣包進文件裡,編譯後就比較像正經的論文插圖了。這裡用到的指令各有分工:set size 決定圖片尺寸,set format xy 設定軸上文字的格式,set title 是標題,set xlabel 與 set ylabel 分別是兩軸說明。
科技論文的圖常常同時有好幾條線,做法很簡單,plot 後面用逗號分隔即可——注意是西文逗號,不是中文逗號:
gnuplot> set terminal latex
gnuplot> set output "combine.tex"
gnuplot> set format xy "$%g$"
gnuplot> set title "Combination"
gnuplot> set xlabel "$x$ axis"
gnuplot> set ylabel "$y$ axis"
gnuplot> plot [-3.14:3.14] 0.2*x with points, sin(x) with lines
with 後面接的是繪圖樣式,points 畫點、lines 畫線,還有 boxes、impulses 等更多選擇可以試。
預設的刻度往往不是我們想要的,這時用 set xtics 指定起點與間距:
gnuplot> set terminal latex
gnuplot> set output "tic.tex"
gnuplot> set format y "$%g$"
gnuplot> set format x "$%.2f$"
gnuplot> set title "This is $\sin(x)$"
gnuplot> set xlabel "This is the $x$ axis"
gnuplot> set ylabel "$\sin(x)$"
gnuplot> set xtics -pi, pi/4
gnuplot> plot [-pi:pi] sin(x)
把 tex 檔插入 LaTeX 文件,效果立刻專業起來。這裡唯一的關鍵是 set xtics:從 -pi 開始、每隔 pi/4 出現一個刻度。pi 是 Gnuplot 內建的常數,直接打 pi 它就懂。
把這幾個套路記熟,你已經能應付九成以上的論文插圖需求了。