How to draw stacked histogram on Gnuplot

Question: How can I draw a stacked histogram (stacked bar chart) using Gnuplot?

In a stacked bar chart, data is visualized with items stacked on top of one another or side-by-side, and different items are differentiated by colors or patterns. Stacked histograms are useful when the sum of item values is as important as the values of individual items.

Here is how to create a stacked bar chart on Gnuplot.

Let's assume that you have the following data file, and want to create a row-stacked histogram using the data on Gnuplot.

#       March   Apri    May
Bob     5       10      30
Alice   20      5       20
Tony    10      10      15
Cathy   15      15      10

The following Gnuplot code snippet generates a stacked histogram plot, as shown below.

set terminal jpeg giant font "Helvetica" 16

set output 'plot.jpg'
set key left

set grid y
set style data histograms
set style histogram rowstacked
set boxwidth 0.5
set style fill solid 1.0 border -1
set ytics 10 nomirror
set yrange [:60]
set ylabel "Number of Referrals"
set ytics 10

plot 'my.dat' using 2 t "March", '' using 3 t "April", '' using 4:xtic(1) t "May"

If you want to generate a stacked bar-chart in black-and-white patterns, use the following Gnuplot script instead.

set terminal jpeg giant font "Helvetica" 16

set output 'plot.jpg'
set key left

set style line 2 lc rgb 'black' lt 1 lw 1
set grid y
set style data histograms
set style histogram rowstacked
set boxwidth 0.5
set style fill pattern border -1
set ytics 10 nomirror
set yrange [:60]
set ylabel "Number of Referrals"
set ytics 10

plot 'my.dat' using 2 t "March" ls 2, '' using 3 t "April" ls 2, '' using 4:xtic(1) t "May" ls 2

Download this article as ad-free PDF (made possible by your kind donation): 
Download PDF

Subscribe to Ask Xmodulo

Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.


Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

Leave a comment

Your email address will not be published. Required fields are marked *