Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count columns in csv in gnuplot

Tags:

gnuplot

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?

like image 289
sashkello Avatar asked Sep 23 '26 04:09

sashkello


2 Answers

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.

like image 148
mgilson Avatar answered Sep 24 '26 18:09

mgilson


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

like image 33
Thor Avatar answered Sep 24 '26 19:09

Thor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!