Search code examples
gnuplotbar-chart

Horizontal bar chart in gnuplot


When Googling "horizontal gnuplot bar chart", the first result I could find http://www.phyast.pitt.edu/~zov1/gnuplot/html/histogram.html suggests rotating (!) the final bar chart which seems rather baroque. Nonetheless I tried the approach but the labels are cut off.

first attempt at a horizontal bar chart in gnuplot 5.2

reset
$heights << EOD
dad                     181
mom                     170
son                     100
daughter        60
EOD

set yrange [0:*]      # start at zero, find max from the data
set boxwidth 0.5      # use a fixed width for boxes
unset key             # turn off all titles
set style fill solid  # solid color boxes

set colors podo

set xtic rotate by 90 scale 0
unset ytics
set y2tics rotate by 90

plot '$heights' using 0:2:($0+1):xtic(1) with boxes lc variable

Is there a better approach?


Solution

  • The link you are referring to is from approx. 2009. gnuplot has developed since then. As @Christoph suggested, check help boxxyerror.

    Script: (edit: shortened by using 4-columns syntax for boxxyerror, i.e. x:y:+/-dx:+/-dy)

    ### horizontal bar graph
    reset session
    
    $Data << EOD
    dad         181
    mom         170
    son         100
    daughter     60
    EOD
    
    set yrange [0:*]      # start at zero, find max from the data
    set style fill solid  # solid color boxes
    unset key             # turn off all titles
    
    myBoxWidth = 0.8
    set offsets 0,0,0.5-myBoxWidth/2.,0.5
    
    plot $Data using (0.5*$2):0:(0.5*$2):(myBoxWidth/2.):($0+1):ytic(1) with boxxy lc var
    ### end of script
    

    Result:

    enter image description here

    Addition:

    what does 2:0:(0):2:($0-myBoxWidth/2.):($0+myBoxWidth/2.):($0+1):ytic(1) mean?

    Well, it looks more complicated than it is. Check help boxxyerror. From the manual:

    6 columns: x y xlow xhigh ylow yhigh

    So, altogether:

    1. x take value from column 2, but not so relevant here since we will use the xyerror box
    2. y take pseudocolumn 0 which is line number starting from zero, check help pseudocolumns, but not so relevant here as well
    3. xlow (0) means fixed value of zero
    4. xhigh value from column 2
    5. ylow ($0-myBoxWidth/2.), line number minus half of the boxwidth
    6. yhigh ($0+myBoxWidth/2.), line number plus half of the boxwidth
    7. ($0+1) together with ... lc var: color depending on line number starting from 1
    8. ytic(1): column 1 as ytic label

    For some reason (which I don't know) gnuplot still doesn't seem to have a convenient horizontal histogram plotting style, but at least it offers this boxxyerror workaround.