通过使用GnuPlot调用其标题来绘制列

Alf*_* M. 8 gnuplot

我有这种格式的文件:

x y1 y2 y3 ei1 ei2 ei3 es1 es2 es3
1 4 5 4 7 7 2 4 7 7
2 7 3 3 3 8 3 3 3 8
3 2 1 4 4 9 6 4 4 9
Run Code Online (Sandbox Code Playgroud)

我想生成类似于以下命令所给出的图

plot "filename" using 1:2:5:8  with yerrorbars
Run Code Online (Sandbox Code Playgroud)

但使用的列标题(x,y1,ei1es1)给他们打电话.如何才能做到这一点?

gnuplot手册的第84页(记录using命令)读取:

Height Weight Age
val1   val1   val1
...    ...    ...
Run Code Online (Sandbox Code Playgroud)

那么下面的绘图命令都是等价的

plot ’datafile’ using 3:1, ’’ using 3:2

plot ’datafile’ using (column("Age")):(column(1)), \
’’ using (column("Age")):(column(2))

plot ’datafile’ using "Age":"Height", ’’ using "Age":"Weight"
Run Code Online (Sandbox Code Playgroud)

然而,当我尝试它们时,我只得到行指数与自己.

mgi*_*son 5

快速浏览一下gnuplot 4.4 vs gnuplot 4.6(当前稳定版本)的文档,看来您尝试使用的功能可能是在gnuplot 4.5中引入的(奇数是开发分支 - 当它们被认为是稳定的时,它们会增加到偶数).能想到实现这一目标的唯一方法是用其他语言编写一个简单的脚本,返回列号(到stdout).这是一个使用python的简单示例,但我很肯定awk如果您想要保持在全POSIX环境中,您可以执行此操作:

#python indexing is 0 based, gnuplot datafile indexing 1 based
COL_AGE=`python -c 'print(open("datafile").readline().split().index("AGE")+1)'`
COL_HEIGHT=`python -c 'print(open("datafile").readline().split().index("HEIGHT")+1)'`
plot "datafile" u COL_AGE:COL_HEIGHT
Run Code Online (Sandbox Code Playgroud)

这个小脚本没有任何花哨的东西(例如,它假设列标题位于第一行),但是使用python的强大功能,可以很容易地进一步扩展脚本:

#!/usr/bin/env python
import sys
with open(sys.argv[1]) as f
   for line in f:
       if (line.strip()):
           print (line.split().index(sys.argv[2])+1)
           sys.exit(0)
Run Code Online (Sandbox Code Playgroud)

现在,您可以将此脚本称为: python script.py datafile AGE以查找"AGE"所在的列.如果"AGE"不在任何列中,则会出错.