我不想在这里做任何花哨的事情。我正在尝试在以下脚本中自动绘制一些实验数据:
print "processing: ", filename
gnuplot = Popen(gnuplot_bin,stdin = PIPE).stdin
if state_plot:
gnuplot.write( "set term x11\n".encode())
gnuplot.write( "set term png size 1920,1010 \n".encode() )
gnuplot.write( "set output \"acceleration.png\" \n".encode() )
gnuplot.write( "set xlabel \"timesteps\" \n".encode() )
gnuplot.write( "set ylabel \"acceleration\" \n".encode() )
gnuplot.write( "plot " %filename " using 1 with lines lt -1 lw 0.5 title 'X axis' \n " .encode() )
gnuplot.write( " " %filename " using 2 with lines lt 1 lw 0.5 title 'Y axis' \n " .encode() )
gnuplot.write( " " %filename " using 3 with lines lt 2 lw 0.5 title 'Z axis' \n " .encode() )
但是文件名是按字面意思取的。我从 gnuplot 得到以下错误:
line 0: warning: Skipping unreadable file "" %filename "" line 0: No data in plot
我已经从 sys.argv 中解析了文件名并确保它是正确和安全的,现在我需要告诉 gnuplot 绘制文件名设置的任何名称。 我试过使用转义字符,删除琥珀色,但显然我使用了错误的语法。
有人可以帮忙吗?
编辑:
感谢 agf 我已经解决了 python 格式问题:
gnuplot.write( "plot \"%s\" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\ \n " %filename )
gnuplot.write( "\"%s\" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\ \n " %filename )
gnuplot.write( "\"%s\" using 3 with lines lt 2 lw 0.5 title 'Z axis' \n " %filename )
但是现在我遇到了 gnuplot 的问题。通常直接使用 gnuplot 时,我会输入:
gnuplot> plot "state_log_6548032.data" using 4 with lines lt -1 lw 0.5 title "X axis" ,\
>"state_log_6548032.data" using 5 with lines lt 1 lw 0.5 title "Y axis" ,\
>"state_log_6548032.data" using 6 with lines lt 2 lw 0.5 title "Z axis"
但是,通过 python 将这些命令发送到 gnuplot 似乎会导致错误:
gnuplot> plot "state_log_6548032.data" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\
^
line 0: invalid character \
gnuplot> "state_log_6548032.data" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\
^
line 0: invalid character \
gnuplot> "state_log_6548032.data" using 3 with lines lt 2 lw 0.5 title 'Z axis'
^
line 0: invalid command
我打赌它与 ,\和换行符有关?
请您参考如下方法:
你想要
gnuplot.write("plot %s using 1 with lines lt -1 lw 0.5 title 'X axis' \n " % filename1)
参见 http://docs.python.org/library/string.html#formatstrings用于新样式格式和 http://docs.python.org/library/stdtypes.html#string-formatting对于旧样式格式,这看起来像您正在尝试做的。
编辑 2:我也喜欢 wiso 的部分建议。将 gnuplot 命令保存在一个文件中(带有您需要放入的变量的格式代码),然后只需使用 Python 读取该文件并对其进行格式化。这将 gnuplot 内容分开,您无需担心引号或行尾。
如果你想发送很多命令,我会尝试将所有字符串放在一个列表中(最好使用 file.readlines() 从文件中读取它们)然后:
for line in lines:
gnuplot.write(lines)
gnuplot.flush()
因此它一次发送一行,但您不必硬编码某个数字。
