Showing posts with label bar chart. Show all posts
Showing posts with label bar chart. Show all posts

Sunday, October 30, 2011

Add value labels to the top of bars in a bar chart

It is easy to plot a bar chart with gnuplot using plot style boxes or histogram. This time we talk about how to add values labels to the top of bars in a bar chart.

The first coming idea is adding labels manually using command "set label ...". This a method but a poor efficient one. A better one is plot the labels with plot style "labels". And this is the method we will talk about here. A sample script is shown below.
reset
set term png font "Times,18"    #set terminal and output file
set output "bar_labels.png"
set xlabel "x value"    #set x and y label
set ylabel "Frequency"
set xrange [-0.5:4.5]    #set x and y range
set yrange [0:4]
set xtics 0,1,4    #set xtics
set style fill solid    #set plot style
set boxwidth 0.5
unset key    #legend not plotted
plot "bar_data.dat" using 1:2 with boxes,\
     "bar_data.dat" using 1:2:2 with labels
#plot bar chart and the value labels on the bars
In this script, we have used a data file (bar_data.dat) like this one
0    2
1    3
2    3
3    2
4    2

Run the script, we get picture file bar_labels.png like the following one.

Gnuplot bar chart with value labels

If you do not like the position of the labels in the upper picture, you can just change it. For example,
lot "bar_data.dat" using 1:2 with boxes,\
     "bar_data.dat" using 1:($2+0.25):2 with labels
will put the labels 0.25 units higher.

Value labels with a 0.25 units higher position
Creative Commons License
Except as otherwise noted, the content of this page is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.