Search code examples
bar-chartgnuplothistogram

gnuplot histogram: assign different colors to different bars


I have the following gnuplot script:

set title font "Monospaced,13" 'Total duration'
set terminal png size 650,350 enhanced font "Monospaced,13"
set grid
set key right top
set style data histograms
set style histogram cluster gap 2
set style fill solid border 2
set xtics format ""
set grid ytics
set ylabel "Milliseconds"
set yrange [0:70000]

ArrayListColor   = "#491d75";
IndexedListColor = "#b32929";
LinkedListColor  = "#d49435";
TreeListColor    = "#12520b";

plot 'TotalDurationBarPlot.dat' using 1 title "Indexed list" linecolor rgb IndexedListColor, '' using 2 title "Tree list" linecolor rgb TreeListColor, '' using 3 title "Array list" linecolor rgb ArrayListColor, '' using 4 title "Linked list" linecolor rgb LinkedListColor, '' u 0:1:1 with labels offset -6.0,-100.0 title ""

set output 'TotalDuration.png'
replot
exit

The data file TotalDurationBarPlot.dat is:

# ILL TL AL LL
934 3692 12274 48188

... and it produces:

enter image description here

Q: I would like to color the four bars. How could I do it?


Solution

  • Why do you want to use histogram plotting style if you have a simple bar chart which you can simply draw with boxes? And why don't you stay with the data format as in your earlier question?

    This could also be of interest (almost duplicate): gnuplot: Colour-coding specific / individual histogram bars

    Edit: even simpler, add another column with the hexadecimal RGB color code.

    Further reading: help int, help xticlabels, help linecolor variable, help colorspec.

    Script:

    ### bar chart with variable box color
    reset session
    
    $Data <<EOD
    "Indexed list"    934   0xb32929
    "Tree list"      3692   0x12520b
    "Array list"    12274   0x491d75
    "Linked list"   48188   0xd49435
    EOD
    
    set style fill solid 1.0
    set boxwidth 0.8
    set key noautotitle
    set grid x,y
    set tics out
    set yrange[0:60000]
    
    plot $Data u 0:2:3:xtic(1) w boxes lc rgb var, \
            '' u 0:2:2 w labels offset 0,0.7
    ### end of script
    

    Result:

    enter image description here