# How to create a custom histogram (normalized)

Let's create some sample data

n = 1000;
data = Table[{RandomReal[{-2, 2}], RandomReal[{-2, 2}],
RandomInteger[{0, 100}]}, {i, 0, n}];
datan = Table[data[[i, 3]], {i, 1, Length[data]}];


Now we plot a Histogram showing how many times every integer (third element of the list) appears.

The histogram is fine however in the vertical axis it shows the absolute values. For example the integer $20$ appears $n = 92$ times.

I want the relative values in the vertical axis. The relative value is the absolute value n divided by the total number $N$ (in this example $N = 1000$).

# Solution

Histogram[datan, Automatic, "Probability"]


To show the most common value in the Histogram, I define an Epilog with a Red Line at the $x$ position of the Commonest value.

Histogram[
datan
, Automatic
, "Probability"
, Epilog -> {Red, Line[{{#, 0}, {#, 1}} &@Last@Commonest[datan]]}
, Frame -> True
]


{{#, 0}, {#, 1}} &@Last@Commonest[datan]

{{59, 0}, {59, 1}}


# Documentation

Histogram

• Very quick and elegant! Any chance showing the average value on the histogram? Commented Feb 18, 2016 at 11:17
• You mean the average height of the bins? @Vaggelis_Z Commented Feb 18, 2016 at 11:23
• I would like to show (preferable with a vertical line) the n integer with the highest probability. Commented Feb 18, 2016 at 11:26
• I have edited the answer. Next time please avoid moving the goalpost and state your needs specifically in the question, not the comments. Commented Feb 18, 2016 at 11:34

rhermans shows a nice built-in way to make this particular histogram, but you can make any custom histogram by the following method.

You can extract the original data from HistogramList,

n = 1000;
data = Table[{RandomReal[{-2, 2}], RandomReal[{-2, 2}],
RandomInteger[{0, 100}]}, {i, 0, n}];
datan = Table[data[[i, 3]], {i, 1, Length[data]}];
Histogram@datan
histdata = HistogramList@datan


(*{{0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110}, {98, 91, 102, 109, 88, 103, 94, 111, 104, 93, 8}*)


Now you can do whatever transformations you like on this. For this example

histdata = {#1, #2/1000} & @@ histdata
(* {{0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110}, {1/10,
21/200, 29/250, 101/1000, 51/500, 49/500, 43/500, 49/500, 87/1000,
89/1000, 19/1000}} *)


and then use this function to make a custom histogram,

histogram[{bins_, bincounts_}, plotopts : OptionsPattern[]] :=
Module[{width = First@Differences@bins},
Graphics[{EdgeForm[Black], RGBColor[0.98, 0.8, 0.49],
Rectangle[{#1 - 0.5 width, 0}, {#1 + 0.5 width, #2}] & @@@
Transpose[{Mean /@ (Partition[bins, 2, 1]), bincounts}]},
plotopts, Frame -> True, AspectRatio -> 0.7]];

histogram[histdata]