2
votes

Is there a function in gnuplot which returns the number of columns in a csv file? I can't find anything in the docs, maybe someone can propose a custom made function for this?

2
I don't think Gnuplot has any variable that tells you this. You could use the answer to this question as a workaround.Thor

2 Answers

5
votes

As of gnuplot4.6, you can make a little hack script to do this. It is certainly not the most efficient, but it is pure gnuplot:

#script col_counter.gp
col_count=1
good_data=1
while (good_data){
   stats "$0" u (valid(col_count))
   if ( STATS_max ){
      col_count = col_count+1
   } else {
      col_count = col_count-1
      good_data = 0
   }
}

Now in your main script,

call "col_counter.gp" "my_datafile_name"
print col_count   #number of columns is stored in col_count.

This has some limitations -- It will choke if you have a column in the datafile that is completely non-numeric followed by more valid columns for example, but I think that it should work for many typical use cases.

print col_count

As a final note, you can use the environment variable GNUPLOT_LIB and then you don't even need to have col_counter.gp in the current directory.

4
votes

Assuming this is related to this question, and that the content of infile.csv is:

n,John Smith stats,Sam Williams stats,Joe Jackson stats
1,23.4,44.1,35.1 
2,32.1,33.5,38.5 
3,42.0,42.1,42.1 

You could do it like this:

plot.gp

nc = "`awk -F, 'NR == 1 { print NF; exit }' infile.csv`"
set key autotitle columnhead
set datafile separator ','
plot for [i=2:nc] "< sed -r '1 s/,([^ ]+)[^,]+/,\\1/g' infile.csv" using 1:i with lines

Note that the \1 needs escaping when used within " in Gnuplot.

Output:

Data file plot