# Creating a custom histogram

Let's create some sample data

Clear["Global*"];
n = 10000;
data0 = Table[{RandomReal[{-1, 1}], RandomReal[{-1, 1}],
RandomInteger[{0, 50}], RandomInteger[{-2, 5}]}, {i, 1, n}];


and make a selection

data = Select[data0, (#[[4]] > 0) &];


Now let's create the histogram

datan = Table[Abs[data[[i, 3]]], {i, 1, Length[data]}];
P0 = Histogram[datan, Automatic, "Probability", ChartStyle -> Gray,
ChartBaseStyle -> EdgeForm[None], Frame -> True,
FrameLabel -> {"t", "P"}, RotateLabel -> False,
LabelStyle -> Directive[FontFamily -> "Helvetica", 20],
Epilog -> {Red, Thick, Dashed,
Line[{{#, 0}, {#, 1}} &@Last@Commonest[datan]]}, PlotRange -> All,
PlotRangePadding -> 0.001, AspectRatio -> 1, ImageSize -> 550]


The histogram corresponds to those data for which the fourth column is an integer 1, 2, 3, 4, or 5. Now I want the following: Split each column of the histogram in five bits (with different color), thus showing the contribution of each of the five possibilities (1, 2, 3, 4, 5).

I use version 9.

Any suggestions?

You may use WeightedData and GatherBy. Both of these were available in version 9.

n = 10000;
SeedRandom[123]
data0 = ArrayFlatten[{{
RandomReal[{-1, 1}, {n, 2}],
RandomInteger[{0, 50}, {n, 1}],
RandomInteger[{-2, 5}, {n, 1}]}}];
data = Select[data0, (#[[4]] > 0) &];


I scale the weights to the probabilities and use "Count" so that the stacked values are the correct probabilities.

WeightedData[#[[All, 1, 2]], #[[All, 2]]/Length@data] & /@
Sort /@
Sort@Map[
First@# -> Length@# &,
GatherBy[data[[All, {4, 3}]], {First, Last}],
{2}] //
Histogram[#, {1}, "Count",
ChartLayout -> "Stacked",
ChartLegends -> Range@5,
ChartBaseStyle -> EdgeForm[Gray],
Epilog -> {Red, Thick, Dashed,
Line[{{#, 0}, {#, 1}} &@Last@Commonest[data[[All, 3]]]]}] &


This compares directly to the unstacked probability histogram.

Histogram[data[[All, 3]], {1}, "Probability",
Epilog -> {Red, Thick, Dashed,
Line[{{#, 0}, {#, 1}} &@Last@Commonest[data[[All, 3]]]]}]


Hope this helps.

I would personally just split the data by the fourth column as

Do[ dat[i] = Select[data, (#[[4]] == i) &][[All, 3]]; , {i, 1, 5}]


and then plot them using the option ChartLayout -> "Stacked"

Histogram[Table[dat[i], {i, 1, 5}], Automatic, "Probability", ChartBaseStyle -> EdgeForm[None], Frame -> True, FrameLabel -> {"t", "P"}, RotateLabel -> False, LabelStyle -> Directive[FontFamily -> "Helvetica", 20], Epilog -> {Red, Thick, Dashed, Line[{{#, 0}, {#, 1}}@Last@Commonest[datan]]}, PlotRange -> All, PlotRangePadding -> 0.001, AspectRatio -> 1, ImageSize -> 550,  ChartLayout -> "Stacked"]


You can then style it with ChartStyle` as you wish.