2
$\begingroup$

In mathematica I have plotted a histogram with the PDF option from a list of values.

How can I extract the heights of the bars in the histogram so that I can compare them with those of another histogram?

$\endgroup$
2
  • 3
    $\begingroup$ Maybe you could use BinCounts $\endgroup$
    – mattiav27
    Dec 7, 2021 at 13:04
  • $\begingroup$ @mattiav27 That is helpful. I don’t even need a histogram anymore! $\endgroup$
    – Amarillo45
    Dec 7, 2021 at 13:18

2 Answers 2

3
$\begingroup$

Try examplary

h = Histogram[RandomVariate[NormalDistribution[0, 1], 200]]

enter image description here

The bars might be found inside h as Rectangle-objects:

bars=Cases[Normal@h , Rectangle[a_, b_, c_] :> {a, b}, Infinity]    (*{{{-3., 0}, {-2.5, 2.}}, {{-2.5, 0}, {-2., 2.}}, {{-2., 0}, {-1.5, 
10.}}, {{-1.5, 0}, {-1., 11.}}, {{-1., 0}, {-0.5, 31.}}, {{-0.5, 
0}, {0., 39.}}, {{0., 0}, {0.5, 34.}}, {{0.5, 0}, {1., 34.}}, {{1.,
0}, {1.5, 24.}}, {{1.5, 0}, {2., 10.}}, {{2., 0}, {2.5, 
2.}}, {{3.5, 0}, {4., 1.}}}*)

The heights follow to

Map[#[[2, 2]] &, bars]
(*{2., 2., 10., 11., 31., 39., 34., 34., 24., 10., 2., 1.}*)

Hope it helps!

$\endgroup$
3
$\begingroup$
SeedRandom[1]
data = RandomVariate[NormalDistribution[0, 1], 200];

You can use HistogramList directly on data:

HistogramList[data][[2]]
{2, 6, 25, 15, 45, 35, 39, 20, 7, 3, 3}

If you have access only to an histogram output (not data) , you can extract the Tooltip labels to get the bar heights:

h = Histogram[data]

enter image description here

Cases[h, Tooltip[_, Style[t_, ___]] :> t, All]
{2, 6, 25, 15, 45, 35, 39, 20, 7, 3, 3}

Note: Default bin specifications for BinCounts and HistogramList are different:

enter image description here

enter image description here

So BinCounts does not give the same output:

{BinCounts[data], HistogramList[data][[2]]}
{{2, 31, 60, 74, 27, 6}, {2, 6, 25, 15, 45, 35, 39, 20, 7, 3, 3}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.