Search code examples
gnuplot

Add horizontal line to bar plot


I want to add a horizontal line to a bar chart to use it as a base measure.

I have this code:

# Scale font and line width (dpi) by changing the size! It will always display stretched.
set terminal svg size 600,500 enhanced fname 'arial'
set term png medium background '#ffffff'
set output 'imageslog.png'
set style data histograms

# Key means label...
set key inside top left
set boxwidth 0.5
set ylabel 'size (logscale)'
set ytics ("0" 0, "1MB" 1000000, "10MB" 10000000)
set ytics ("0" 0, "1B" 1, "10B" 10, "100B" 100, "1KB" 1000, "10KB" 10000, "100KB" 100000,"1MB" 1000000, "10MB" 10000000)
set logscale y
set yrange [0:15000000]
set yrange [0:200000000]
#set xrange [1979:2018]
set xtics out 5
set xlabel 'size'
set title 'Peso de la imagen por plataforma'
plot 'data.txt' using 2:xtic(1)  title "original" with histograms fs pattern 1, \
'data.txt' using 3  title "instagram" with histograms fs pattern 1, \
'data.txt' using 4  title "twitter" with histograms fs pattern 1

With data.txt:

1 8793374  102775 103864
2 7761601  86368 81342
3 13071794  158629 169718
4 12989031 171437 183929
media 10653950 129802 134713%

That produces a stacker bar chart. I would like to add a horizontal line across the whole chart with a constant value to set up a baseline. How can I do it?


Solution

  • There are at least two ways to create a line as you want:

    1. set arrow without arrow, i.e. nohead, check help arrow.
    2. simply plot a constant value

    By the way, you don't have to define the ytic labels with the prefixes yourself. gnuplot has the prefixes in the format specifier %c, check help format_specifiers.

    Code:

    ### add a horizontal line
    reset session
    
    $Data <<EOD
    1 8793374  102775 103864
    2 7761601  86368 81342
    3 13071794  158629 169718
    4 12989031 171437 183929
    media 10653950 129802 134713
    EOD
    
    set style data histograms
    
    set key inside top left
    set boxwidth 0.5
    set ylabel 'size (logscale)'
    set format y "%.0s %cB"
    set logscale y
    set yrange [0.2:900e6]
    set xtics out 5
    set xlabel 'size'
    set title 'Peso de la imagen por plataforma'
    
    set arrow 1 from graph 0, first 100 to graph 1, first 100 nohead lc "blue" front
    set label 1 at graph 0, first 100 "another\nline" tc "blue" offset 2,-0.5
    
    plot $Data u 2:xtic(1) w histograms fs pattern 1 ti "original" , \
            '' u 3         w histograms fs pattern 1 ti "instagram" , \
            '' u 4         w histograms fs pattern 1 ti "twitter", \
            10000          w l          lc "red"     ti "some line"
    ### end of code
    

    Result:

    enter image description here