gnuplotのグラフにPNG・JPGファイルなどを埋め込む

gnuplot 4.4 以降ではPNGファイルやJPGファイルなどを「プロット」することができます。この機能を使うと画像をグラフに埋め込むことができます。

埋め込める画像形式のチェック

埋め込める画像形式を調べるにはgnuplotのコマンドプロンプトから

show datafile binary filetype

と打ち込みます。すると以下のように使用できる画像形式の一覧が表示されます。以下の例では有名どころではJPG、PNG、GIFなどの形式が使えるようになっています。

画像ファイルの埋め込み

以下ではPNGファイルを例にとって説明します。PNGファイルを「プロット」するにはplot "ファイル名" binary filetype=png with rgbimageというコマンドを使います。以下に例を示します。

plot "test-embed.png" binary filetype=png with rgbimage

この例ではこちらのような480×360ピクセルのPNGファイルtest-embed.pngをプロットしています。このスクリプトを実行すると、以下のようなグラフが生成されます。グラフの中に画像が埋め込まれていることがわかります。

もしPNG以外の画像形式ならば、filetype=pngの部分を例えばfiletype=jpgなどに変えます。もしくはfiletype=autoとすると、ファイルの拡張子から勝手に画像形式を判断してくれるようです。

図のアスペクト比を保存して埋め込む

論文などに使うグラフにPNGの図を挿入図として埋め込む場合など、図のアスペクト比を保存したい場合が多いです。そのような場合は、multiplotを用いて図の貼りこみ部分を分離し、図の貼りこみ部分でset size ratio -1およびset autoscale xyを用いて、埋め込まれた図の縦横比が元の画像の縦横比と一致するようにします。

まず、400×400ピクセルのPNGファイルaspect-ratio_400x400.pngを埋め込む場合を考えます。このファイルは下のように円と正方形から成っています。

このファイルをPostScriptファイルに埋め込む場合の例は以下の通りです。

#version 4.4.0

set multiplot

set xlabel "x axis"
set ylabel "y axis"
set xrange [0:10]
set yrange [-1:1]

# 関数の表示
plot cos(x*4)*exp(-x) with lp notitle

# 画像の貼りこむ大きさと位置を指定
set size 0.3,0.3
set origin 0.45,0.2

# borderやmarginなどを消す
set tmargin 0
set bmargin 0
set rmargin 0
set lmargin 0
set border 0
set format x ""
set format y ""
unset xtics
unset ytics
unset xlabel
unset ylabel

# アスペクト比を保存する
set size ratio -1
set autoscale xy

# 画像の表示
plot "aspect-ratio_400x400.png" binary filetype=png with rgbimage notitle


unset multiplot


reset

# TeminalとOutputを変更してこのファイルを再読み込みし、PostScriptファイルを作る
if (exist("TERM")==0) \
     pause -1;\
     TERM = "PS";\
     set term post color enhanced eps "Arial" 25;\
     set out "embed-png-aspect-ratio.eps";\
     reread

# TeminalとOutputを元に戻す
set out
set term win 
undefine TERM

画像のプロット前にset size ratio -1としてアスペクト比が保存されるようにします。さらにset autoscale xyとすることで、画像全体が表示されるようにしています。また、set tmargin 0unset ylabelの部分で余計なメモリや軸やマージンなどを消しています。

このスクリプトによって作製されたEPSファイルは以下のようになっています。画像がアスペクト比を保存された状態(今の場合、縦横比1:1)で貼りこまれていることが分かります。

同様に、下のような400×204ピクセルのPNGファイルを埋め込む場合も同様です。

#version 4.4.0

set multiplot

set xlabel "x axis"
set ylabel "y axis"
set xrange [0:10]
set yrange [-1:1]

# 関数の表示
plot cos(x*4)*exp(-x) with lp notitle

# 画像の貼りこむ大きさと位置を指定
set size 0.3,0.3
set origin 0.45,0.2

# borderやmarginなどを消す
set tmargin 0
set bmargin 0
set rmargin 0
set lmargin 0
set border 0
set format x ""
set format y ""
unset xtics
unset ytics
unset xlabel
unset ylabel

# アスペクト比を保存する
set size ratio -1
set autoscale xy

# 画像の表示
plot "aspect-ratio_400x204.png" binary filetype=png with rgbimage notitle


unset multiplot


reset

# TeminalとOutputを変更してこのファイルを再読み込みし、PostScriptファイルを作る
if (exist("TERM")==0) \
     pause -1;\
     TERM = "PS";\
     set term post color enhanced eps "Arial" 25;\
     set out "embed-png-aspect-ratio2.eps";\
     reread

# TeminalとOutputを元に戻す
set out
set term win 
undefine TERM

このスクリプトによって作製されたEPSファイルでも、以下のように画像はアスペクト比を保存された状態で貼りこまれています。