5

This question is related to gnuplot histogram: How to put values on top of bars.

I have a datafile file.dat:

x y1 y2
1 2 3
2 3 4
3 4 5

and the gnuplot:

set style data histogram;
set style histogram rowstacked;
plot newhistogram 'foo', 'file.dat' u 2:xtic(1) t col, '' u 3 t col;

Now I want to place the sums of columns 2 and 3 above the bars. The obvious solution

plot newhistogram 'foo', 'file.dat' u 2:xtic(1) t col, '' u 3 t col, \
'' u ($0-1):($2+$3+0.2):($2+$3) notitle w labels font "Arial,8";

puts the labels in the correct place, but the calculated sum is wrong. That is, in ($0-1):($2+$3+0.2):($2+$3), the second $2 appears to evaluate to zero.

What's going wrong here and how do I fix it?

Alexander Klauer
  • 957
  • 11
  • 18

1 Answers1

4

You must give an explicit string as label:

 plot newhistogram 'foo', 'file.dat' u 2:xtic(1) t col, '' u 3 t col, \
'' u ($0-1):($2+$3):(sprintf('%.1f', $2+$3)) notitle w labels offset 0,1 font "Arial,8"

As other improvement, I would use the offset option which allows you to give an displacement in character units, which doesn't depend on the yrange.

(Side note: if a value from a column is used, then one can skip the explicit formatting of the label, like using 1:2:2 with labels, but in general one should use sprintf to format the label)

Christoph
  • 47,569
  • 8
  • 87
  • 187
  • Note that in the case of a datafile with both positive and negative sums, the correct offset is no longer constant, so unfortunately you cannot use `offset` (which expects a fixed displacement) but must use the yrange-dependent method. – Alexander Klauer Jun 18 '15 at 13:56
  • Yes, you are right. There is a very, very ugly hack: insert some new lines when the value is negative: `sprintf("%s%.1f", ($2+$3) < 0 ? "\n\n" : "", $2+$3)`. Disclaimer: don't try this at home ;) – Christoph Jun 18 '15 at 14:05