通常在使用交互式 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"
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用子进程从 python 执行相同操作时:
gnuplot.write( "plot \"%s\" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\ \n" %filename )
gnuplot.write( "plot \"%s\" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\ \n" %filename )
gnuplot.write( "plot \"%s\" using 3 with lines lt 2 lw 0.5 title 'Z axis' \n" %filename )
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
gnuplot> plot "state_log_6548032.data" using 1 with lines lt -1 lw 0.5 title 'X axis' ,\
^
line 0: invalid character \
gnuplot> plot "state_log_6548032.data" using 2 with lines lt 1 lw 0.5 title 'Y axis' ,\
^
line 0: invalid character \
Run Code Online (Sandbox Code Playgroud)
我花了很多时间试图弄清楚这是否是 python 的问题,但我发现这是 gnuplot 的问题,它在从控制台调用时出于某种原因使用转义字符,但在我的情况下不需要. 但是我的问题仍然存在。如何通过管道指令从 python 子进程或通过从 python 创建一个 gnu 文件并调用 gnuplot 子进程来使用该文件,在连续行中绘制上面的数据^^?
编辑:
对于任何可能会陷入这个简单小事的人来说:正如下面那些让这个社区保持活力的好人所解释的那样,当您使用“\”时,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 )
Run Code Online (Sandbox Code Playgroud)
在您发布的命令行 gnuplot 示例中,您转义换行符以避免屏幕中出现一英里长的行,但仍将数据 tu gnuplot 作为单行发送。
如果您手动输入数据,这很酷,但如果您以编程方式进行,您为什么要关心?只需发送一行,Python 不会抱怨可读性:)。如果您对问题所在感到好奇,那是因为 Python也\用作转义序列,因此字符永远不会到达gnuplot.
也就是说,有 python-gnuplot 库可以为您处理所有这些肮脏的工作。去看一下!