余白の書きなぐり

aueweのブログ

Python3の計算結果をGnuplotでグラフ化(subprocess Popenを使う)

ディスプレイにグラフを表示させる

pythonからgnuplotを使う上で、これが最も簡単な方法。

from subprocess import call
call( ["gnuplot", "-e", "plot sin(x); pause -1"])

qを押せばグラフは消える。

グラフをファイルに保存

gnuplotの設定は長くなるので、 gnuplotCommand という文字列にまとめた。

from subprocess import call

gnuplotCommand ='''
set terminal png;
set output "sin.png";
plot sin(x);
'''

call( [ "gnuplot", "-e", gnuplotCommand])

Pythonで計算したデータをプロット

これが案外ハマる。 UNIX系なら echo で計算結果を標準出力に流して PIPE で gnuplot に食わせれば良いけれど、 Windowsでは echo が使えない(エラーが出る)。 代わりに Gow に含まれる printf 関数を使った。

from subprocess import Popen, PIPE

data = '''
1 5
2 10
3 15
'''

gnuplotCommand = '''
plot '-' ;
pause -1
'''

printData = Popen( [ 'printf', data], stdout=PIPE)
Popen( [ 'gnuplot', '-e', gnuplotCommand], stdin=printData.stdout)