mwarning
mwarning

Reputation: 771

How to sum an entire column in gnuplot?

I have a multiple CSV files like this (just one column):

3
4
2.3
0.1

Now I want to create a gnuplot bar chart that has <filename>:<sum of the column>.

But currently I struggle with summing up a single column:

plot 'data1.txt' using 0:(sum [col = 0:MAXCOL] (col)) with linespoint;

Upvotes: 3

Views: 2931

Answers (2)

mwarning
mwarning

Reputation: 771

With help from @Ethan, I was able to solve my problem:

array files = ['data1.txt', 'data2.txt']
array SUM[|files|]
do for [i=1:|files|] {
  stats files[i] using 1 nooutput
  SUM[i] = STATS_sum
}
set style fill solid
set boxwidth 0.5
set xlabel 'File'
set ylabel 'Sum'
set yrange [0:]
plot SUM using 1:2:xticlabels(files[column(0)+1]) with boxes

data1.txt:

11
22
33
44

data2.txt:

11
2
33
4

enter image description here

Upvotes: 2

Ethan
Ethan

Reputation: 15093

The command you show is summing each row rather than each column.

(1) If you can transpose rows/columns in your csv file before feeding it to gnuplot, this command would produce a plot close to what you ask for. Note that MAXCOL is really the number of rows (not columns) in the original data file

  set boxwidth 0.5
  set style fill solid
  plot 'transpose_of_original' using 0:(sum [col=0:MAXCOL] col) with boxes

(2) Alternatively you can do the summing gnuplot by first accumulating the sums and then plotting it afterward

  # get number of columns
  stats 'data1.txt' nooutput
  NCOL = STATS_columns
  array SUM[NCOL]
  # get sum for each column
  do for [col=1:NCOL] {
      stats 'data1.txt' using col nooutput
      SUM[col] = STATS_sum
  }

  # Now we plot the sums in a bar chart
  set style fill solid
  set boxwidth 0.5
  set xlabel "Column"
  set ylabel "Sum"
  plot SUM using 1:2 with boxes

enter image description here

Upvotes: 5

Related Questions