【问题标题】:gnuplot: how to know the last column number?gnuplot:如何知道最后一列号?
【发布时间】:2021-10-01 15:37:00
【问题描述】:

我在使用 gnuplot 处理数据时遇到问题。 我的数据每行有不同的列号。 我想用第一列的 X 轴和最后一列的 Y 轴进行绘图。 每行最后一列总是不同的。

例如,我的数据看起来像这样 (my.dat)

1 2 
2 1 3
3 4 4
4 5
5 2 1 3 6

plot 'my.dat' us 1:(lastcolumn) w l

在读取 gnuplot 之前,我可以对数据进行预处理。 但我的 gnuplot 是 windows 版本,我不能使用 awk 或任何解析程序。 所以我希望它只处理gnuplot。 这可能吗?

谢谢

【问题讨论】:

    标签: gnuplot


    【解决方案1】:

    是的,您可以使用 gnuplot 进行检查。思路如下:

    您使用stats 分析您的数据,并在using 中使用valid 递归检查哪一列是最后一个有效的列。如果到达无效列,则返回上一列的编号,否则检查下一列。最后一列然后包含在变量STATS_max

    check_valid_column(c) = valid(c) ? check_valid_column(c + 1) : c - 1
    stats 'my.dat' using (check_valid_column(1)) nooutput
    
    last_column = int(STATS_max)
    plot 'my.dat' using 1:last_column
    

    【讨论】:

    • 我从来没有想过这个问题。感谢您的帮助。
    【解决方案2】:

    为了记录,这里有一个替代建议。 Christoph 的解决方案当然更优雅,而且可能更快。 但是,使用递归方法时,如果列数超过 250 列,则会收到错误 "recursion depth limit exceeded"(诚然,这可能是非常罕见的情况)。

    下面的解决方案使用行作为一个字符串,并用words() 计算列。但是,这仅在您将空格作为分隔符时才有效。使用逗号将不起作用。不确定字符串长度限制是多少。

    代码:(编辑:无需绘制到虚拟表,可以使用stats

    ### find the maximum number of columns
    reset session
    
    # create some random test data
    set print $Data
        rows = int(rand(0)*5+5)             # random 5 to 9 lines
        do for [r=1:rows] {
            minCols = 251                   # if minCols >250, the recursive approach will fail
            cols = int(rand(0)*10+minCols)
            line = ''
            do for [c=1:cols] { line = sprintf("%s %d",line,rand(0)*10) }
            print line
        }
    set print
    
    # alternative approach with word(). Works only for separator whitespace.
    set datafile separator "\n"
    maxCol=0
    stats $Data u (cols=words(strcol(1)), cols>maxCol?maxCol=cols:0) nooutput
    set datafile separator whitespace
    print "words() approach:   ", maxCol
    
    # Recursive approach for comparison
    print "Recursive approach: "
    check_valid_column(c) = valid(c) ? check_valid_column(c + 1) : c - 1
    stats $Data u (check_valid_column(1)) nooutput
    last_column = int(STATS_max)
    print last_column
    
    ### end of code
    

    结果:(如果最大列数>250)

    words() approach:    259
    
    Recursive approach: 
             "SO41032862.gp" line 28: recursion depth limit exceeded
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-13
      • 2018-11-08
      • 2021-02-27
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多