Skip to content

Histogram

The histogram object creates the histogram edges and bins when the draw function is called for the first time with lazy evaluation. Lazy evaluation avoids calculating edges unnecessarily in case the user changes the object parameters before calling draw. This object includes several algorithms for automatically delimiting the edges and bins for the histograms.

1
hist(data);

example_histogram_1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#include <cmath>
#include <matplot/matplot.h>
#include <random>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(10000, 0, 1);

    auto h = hist(x);
    std::cout << "Histogram with " << h->num_bins() << " bins" << std::endl;

    show();
    return 0;
}

More examples

example_histogram_2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <cmath>
#include <matplot/matplot.h>
#include <random>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(10000, 0, 1);

    subplot(2, 3, 0);
    hist(x, histogram::binning_algorithm::automatic);
    title("Automatic binning");

    subplot(2, 3, 1);
    hist(x, histogram::binning_algorithm::scott);
    title("Scott's rule");

    subplot(2, 3, 2);
    hist(x, histogram::binning_algorithm::fd);
    title("Freedman-Diaconis rule");

    subplot(2, 3, 3);
    hist(x, histogram::binning_algorithm::integers);
    title("Integers rule");

    subplot(2, 3, 4);
    hist(x, histogram::binning_algorithm::sturges);
    title("Sturges' rule");

    subplot(2, 3, 5);
    hist(x, histogram::binning_algorithm::sqrt);
    title("Square root rule");

    save("histogram_2.svg");

    show();
    return 0;
}

example_histogram_3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <cmath>
#include <matplot/matplot.h>
#include <random>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(10000, 0, 1);

    subplot(2, 3, 0);
    auto a = histogram::binning_algorithm::automatic;
    hist(x, a, histogram::normalization::count);
    title("Count (c_i)");

    subplot(2, 3, 1);
    hist(x, a, histogram::normalization::probability);
    title("Probability (c_i/N)");

    subplot(2, 3, 2);
    hist(x, a, histogram::normalization::cummulative_count);
    title("Cummulative count (∑_{j=1}^i c_j)");

    subplot(2, 3, 3);
    hist(x, a, histogram::normalization::count_density);
    title("Count density (c_i/w_i)");

    subplot(2, 3, 4);
    hist(x, a, histogram::normalization::pdf);
    title("PDF (c_i/(N w_i))");

    subplot(2, 3, 5);
    hist(x, a, histogram::normalization::cdf);
    title("CDF (∑_{j=1}^i c_j/N)");

    show();
    return 0;
}

example_histogram_4

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cmath>
#include <matplot/matplot.h>
#include <random>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(1000, 0, 1);

    size_t num_bins = 25;
    auto h = hist(x, num_bins);

    auto v_it = h->values().begin();
    auto e_it = h->bin_edges().begin();
    while (v_it != h->values().end()) {
        std::cout << "[" << *e_it << ";" << *std::next(e_it)
                  << "] - count: " << *v_it << std::endl;
        ++v_it;
        ++e_it;
    }

    show();
    return 0;
}

example_histogram_5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(1000, 0, 1);

    auto h = hist(x);
    title(num2str(h->num_bins()) + " bins");

    for (size_t i = 0; i < 5; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        title(num2str(h->num_bins()) + " bins");
    }

    h->num_bins(50);
    title(num2str(h->num_bins()) + " bins");

    show();
    return 0;
}

example_histogram_6

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(10000, 0, 1);

    std::vector<double> edges = {-10.0000, -2.0000, -1.7500, -1.5000, -1.2500,
                                 -1.0000,  -0.7500, -0.5000, -0.2500, 0,
                                 0.2500,   0.5000,  0.7500,  1.0000,  1.2500,
                                 1.5000,   1.7500,  2.0000,  10.0000};

    hist(x, edges)->normalization(histogram::normalization::count_density);

    show();
    return 0;
}

example_histogram_7

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<std::string> categories = {
        "no", "no",  "yes",       "yes",       "yes", "no",  "no",
        "no", "no",  "undecided", "undecided", "yes", "no",  "no",
        "no", "yes", "no",        "yes",       "no",  "yes", "no",
        "no", "no",  "yes",       "yes",       "yes", "yes"};
    hist(categories)->bar_width(0.5);

    show();
    return 0;
}

example_histogram_8

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(10000, 0, 1);

    auto h = hist(x, histogram::normalization::probability);
    std::cout << "Sum of bar heights: "
              << std::accumulate(h->values().begin(), h->values().end(), 0.0)
              << std::endl;

    show();
    return 0;
}

example_histogram_9

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(2000, 0, 1);
    std::vector<double> y = randn(5000, 1, 1);

    auto h1 = hist(x);
    hold(on);
    auto h2 = hist(y);
    h1->normalization(histogram::normalization::probability);
    h1->bin_width(0.25);
    h2->normalization(histogram::normalization::probability);
    h2->bin_width(0.25);

    show();
    return 0;
}

example_histogram_10

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(1000, 0, 1);

    auto h = hist(x);
    h->num_bins(15);
    h->bin_edges(iota(-3, 3));
    h->face_color({0., 0., 0.5, 0.5});
    h->edge_color("r");

    show();
    return 0;
}

example_histogram_11

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(5000, 5, 2);

    auto h = hist(x);
    h->normalization(histogram::normalization::pdf);
    hold(on);

    double mu = 5;
    double sigma = 2;
    auto f = [&](double y) {
        return exp(-pow((y - mu), 2.) / (2. * pow(sigma, 2.))) /
               (sigma * sqrt(2. * pi));
    };
    fplot(f, std::array<double, 2>{-5, 15})->line_width(1.5);

    show();
    return 0;
}

example_histogram_12

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cmath>
#include <matplot/matplot.h>
#include <random>
#include <thread>

int main() {
    using namespace matplot;

    std::vector<double> x = randn(1000, 0, 1);

    auto h = hist(x);
    title(num2str(h->num_bins()) + " bins");

    for (size_t i = 0; i < 5; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(3));
        title(num2str(h->num_bins()) + " bins");
    }

    h->num_bins(5);
    title(num2str(h->num_bins()) + " bins");

    show();
    return 0;
}

example_histogram_14

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
#include <iostream>
#include <matplot/matplot.h>
#include <random>

constexpr size_t DEFAULT_BOOTSTRAP_REPLICATES = 1000000;

std::vector<double>
bootstrap(std::function<double()> statistic,
          size_t replicates = DEFAULT_BOOTSTRAP_REPLICATES) {
    std::vector<double> data(replicates);
    std::generate(data.begin(), data.end(), statistic);
    return data;
}

std::vector<double>
bootstrap(std::function<double(std::vector<double>)> statistic,
          std::function<double()> data_source, size_t sample_size,
          size_t replicates = DEFAULT_BOOTSTRAP_REPLICATES) {
    std::vector<double> data(replicates);
    return bootstrap(
        [&]() {
            std::vector<double> data(sample_size);
            std::generate(data.begin(), data.end(), data_source);
            return statistic(data);
        },
        replicates);
}

template <typename NUMBER> double mean(const std::vector<NUMBER> &v) {
    double sum = 0.0;
    for (const auto &item : v) {
        sum += static_cast<double>(item);
    }
    return sum / static_cast<double>(v.size());
}

int main() {
    // Example bootstraping from many distributions.
    // Distributions:
    // https://blog.cloudera.com/blog/2015/12/common-probability-distributions-the-data-scientists-crib-sheet/
    using namespace matplot;

    auto f = figure(true);
    f->width(f->width() * 3);
    f->height(f->height() * 2);
    f->x_position(10);
    f->y_position(10);

    enum histogram::normalization norm = histogram::normalization::probability;
    enum histogram::binning_algorithm alg =
        histogram::binning_algorithm::automatic;
    const size_t n_bins = 200;
    const float hist_alpha = 0.7f;
    std::default_random_engine r;
    std::mt19937 generator(r());

    std::cout << "Averages - Normal" << std::endl;
    subplot(2, 3, 0);
    title("Average - Normal / Gaussian - mean(x)= {∑ x_i}/{n} - x_i = N(0,1)");
    xlim({-4, 4});
    ::matplot::legend({});
    std::normal_distribution<double> d(0, 1);
    std::function<double()> normal_data_source = [&]() { return d(generator); };
    hist(bootstrap(mean<double>, normal_data_source, 1), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, normal_data_source, 2), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("2 samples");
    f->draw();
    hist(bootstrap(mean<double>, normal_data_source, 5), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, normal_data_source, 10), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("10 samples");
    f->draw();
    hist(bootstrap(mean<double>, normal_data_source, 30), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    xlabel("Value");
    ylabel("Frequency");

    std::cout << "Averages - Uniform" << std::endl;
    subplot(2, 3, 1);
    title("Average - Uniform - mean(x)= {∑ x_i}/{n} - x_i = U(-1;+1)");
    xlim({-1, 1});
    ::matplot::legend({});
    std::uniform_real_distribution<double> u(-1.0, 1.0);
    std::function<double()> uniform_data_source = [&]() {
        return u(generator);
    };
    hist(bootstrap(mean<double>, uniform_data_source, 1), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, uniform_data_source, 2), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("2 samples");
    f->draw();
    hist(bootstrap(mean<double>, uniform_data_source, 5), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, uniform_data_source, 10), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("10 samples");
    f->draw();
    hist(bootstrap(mean<double>, uniform_data_source, 30), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    xlabel("Value");
    ylabel("Frequency");

    std::cout << "Sum of squares - Chi-squared distribution" << std::endl;
    subplot(2, 3, 2);
    title("Sum of Squares - Chi-Squared - ∑ (x_i - mean(x))^2");
    xlim({0, 5});
    ::matplot::legend();
    double m = 0;
    auto chi2_data_source = [&]() {
        return pow(normal_data_source() - m, 2.0);
    };
    hist(bootstrap(mean<double>, chi2_data_source, 1), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, chi2_data_source, 2), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("2 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi2_data_source, 5), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi2_data_source, 10), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("10 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi2_data_source, 30), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    // xlim({0,50});
    xlabel("Value");
    ylabel("Frequency");

    std::cout << "Square root of sum of squares (Chi distribution)"
              << std::endl;
    subplot(2, 3, 3);
    title("Square Root of Sum of Squares - Chi - √{∑ (x_i - mean(x))^2}");
    xlim({0, 4});
    ::matplot::legend({});
    auto chi_data_source = [&]() { return sqrt(chi2_data_source()); };
    hist(bootstrap(mean<double>, chi_data_source, 1), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, chi_data_source, 2), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("2 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi_data_source, 5), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi_data_source, 10), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("10 samples");
    f->draw();
    hist(bootstrap(mean<double>, chi_data_source, 30), n_bins)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    xlabel("Value");
    ylabel("Frequency");

    std::cout << "Ratio of scaled sums of squares / variance (F distribution)"
              << std::endl;
    subplot(2, 3, 4);
    title("Variance ratio - F - σ_1 / σ_2");
    ::matplot::legend({});
    m = 0.0;
    auto ratio_ss = [&]() { return chi2_data_source() / chi2_data_source(); };
    xlim({0, 5});
    std::vector<double> edges = linspace(0, 10, n_bins);
    hist(bootstrap(mean<double>, ratio_ss, 1), edges)
        ->bin_limits_min(0)
        .bin_limits_max(5)
        .normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, ratio_ss, 2), edges)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("2 samples");
    f->draw();
    hist(bootstrap(mean<double>, ratio_ss, 5), edges)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, ratio_ss, 10), edges)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("10 samples");
    f->draw();
    hist(bootstrap(mean<double>, ratio_ss, 30), edges)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    xlabel("Value");
    ylabel("Frequency");

    std::cout << "Averages - Bernoulli" << std::endl;
    subplot(2, 3, 5);
    title("Average - Bernoulli - mean(x)= {∑ x_i}/{n} - x_i = B(1/6)");
    xlim({0, 1});
    ::matplot::legend();
    std::bernoulli_distribution b(1. / 6.);
    std::function<double()> bernoulli_data_source = [&]() {
        return static_cast<double>(b(generator));
    };
    hist(bootstrap(mean<double>, bernoulli_data_source, 1), 4)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("1 sample");
    f->draw();
    hold(on);
    hist(bootstrap(mean<double>, bernoulli_data_source, 5), 6)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("5 samples");
    f->draw();
    hist(bootstrap(mean<double>, bernoulli_data_source, 30), 10)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("30 samples");
    f->draw();
    hist(bootstrap(mean<double>, bernoulli_data_source, 300, 100000), 50)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("300 samples");
    f->draw();
    hist(bootstrap(mean<double>, bernoulli_data_source, 3000, 10000), 50)
        ->normalization(norm)
        .algorithm(alg)
        .edge_alpha(1.0)
        .face_alpha(hist_alpha)
        .display_name("3000 samples");
    f->draw();
    xlabel("Value");
    ylabel("Frequency");

    //    save("distributions.png");
    //    save("distributions.pdf");
    //    save("distributions.eps");
    //    save("distributions.gif");
    //    save("distributions.jpg");

    show();
    return 0;
}