Search code examples
gnuplot

Gnuplot bars and line in a single plot, where bars are equidistant


I am trying to plot bars and line in a single plot from the following data:

amount  cost    profit
64  22.915949   48.15697753
128 15.424979   56.41929322
256 9.473054    49.80545598
512 6.685107    96.8453052
1024    4.897494    56.82355225

So far I have come to the following plot:

bars line chart

Using this code:

set boxwidth 40.0 abs
set style fill solid 

set y2tics
set ytics nomirror

set grid y

set bmargin at screen 0.2
set tmargin at screen 0.9

# Set the graph title and axis labels
set title "Title"
set xlabel "Amount"
set ylabel "Cost"
set y2label "Profit"

plot 'data.txt' using 1:2:xtic(1) with boxes axes x1y1, \
     'data.txt' using 1:3 w lp pt 7 lw 2 ps 1 axes x1y2
pause -1

How can I make the bars not be separated but close together with a little constant separation?


Solution

  • Short answer: use the pseudocolumn 0 for the x-values (check help pseudocolumns)

    For example like this:

    Script:

    ### bars and pseudocolumn
    reset session
    
    $Data <<EOD
    amount  cost    profit
      64    22.915949   48.15697753
     128    15.424979   56.41929322
     256    9.473054    49.80545598
     512    6.685107    96.8453052
    1024    4.897494    56.82355225
    EOD
    
    # Set the graph title and axis labels
    set title "Title"
    set xlabel "Amount"
    set ylabel "Cost"
    set ytics nomirror
    set y2label "Profit"
    set y2tics
    
    set boxwidth 0.8
    set style fill solid 0.4
    
    plot $Data u 0:2:xtic(1) w boxes axes x1y1 ti "Cost",\
            '' u 0:3 w lp pt 7 lw 2 axes x1y2  ti "Profit"
    ### end of script
    

    Result:

    enter image description here