Histograms

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder


Random Numbers[edit]

We can produce results similar to those of throwing a six-sided die by using the rand function which returns a random value in the interval (0, 1).

octave:13> rand

Try executing this command several times and observe the results. In order to obtain integer values in the range from 1 to 6 we'll multiply the result of rand by 6, add 1, and then take the floor of this result.

octave:16> floor(6*rand + 1)

Try executing this command several times and observe the results.

Array of Random Numbers[edit]

An array of 10 random throws of a six-sided die can be produced as follows.

octave:17> A = floor(6 * rand(10, 1) + 1)

Plotting a Histogram[edit]

Histograms can easily be plotted from the array. The second argument [1 2 3 4 5 6] provides the midpoints of the 'bins' for our histogram.

octave:18> hist(A, [1 2 3 4 5 6]);

Plotting Multiple Histograms on Same Graph[edit]

 # Plots three histograms of random data from six-sided die                                     
 # Histograms vary in their population
 graphics_toolkit("gnuplot")

 # Generate three random data sets of six-sided die throws
 A = floor(6 * rand(10000, 1) + 1)
 B = floor(6 * rand(100, 1) + 1)
 C = floor(6 * rand(10, 1) + 1)

 # Plot data as histograms
 hold on
 hist(A, [1, 2, 3, 4, 5, 6], "facecolor", "cyan");
 hist(B, [1, 2, 3, 4, 5, 6], "facecolor", "magenta");
 hist(C, [1, 2, 3, 4, 5, 6], "facecolor", "green");

 # Use a logarithmic scale
 set(gca, 'yscale', 'log');

 # Add Titles and Legends
 grid on
 title("Histogram Plots: Six-sided Die Simulations");

 xlabel("Six-sided Die Roll")
 ylabel("Frequency of Occurrence (log scale)")

 legend ("10 thousand samples", "100 samples", "10 samples", "location", "northeastoutside");

 # Print to a file
 print -dpng histogram.png