Skip to content

Commit f442235

Browse files
authored
Merge pull request #15 from ziotom78/fix_histogram
Fix Gnuplot::histogram
2 parents 6d21603 + 6770a06 commit f442235

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

gplot++.h

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
*
2929
* Version history
3030
*
31+
* - 0.9.1 (2025/02/06): bug fixes in method `histogram`
32+
*
3133
* - 0.9.0 (2024/11/19): new method `redirect_to_animated_gif`
3234
*
3335
* - 0.8.0 (2024/10/15): new methods `add_point_xerr`,
@@ -72,7 +74,7 @@
7274
#include <unistd.h>
7375
#endif
7476

75-
const unsigned GNUPLOTPP_VERSION = 0x000900;
77+
const unsigned GNUPLOTPP_VERSION = 0x000901;
7678
const unsigned GNUPLOTPP_MAJOR_VERSION = (GNUPLOTPP_VERSION & 0xFF0000) >> 16;
7779
const unsigned GNUPLOTPP_MINOR_VERSION = (GNUPLOTPP_VERSION & 0x00FF00) >> 8;
7880
const unsigned GNUPLOTPP_PATCH_VERSION = (GNUPLOTPP_VERSION & 0xFF);
@@ -498,18 +500,34 @@ class Gnuplot {
498500
assert(!is_3dplot);
499501
}
500502

501-
double min = *std::min_element(values.begin(), values.end());
502-
double max = *std::max_element(values.begin(), values.end());
503-
double binwidth = (max - min) / nbins;
504-
505-
std::vector<size_t> bins(nbins);
506-
for (const auto &val : values) {
507-
int index = static_cast<int>((val - min) / binwidth);
508-
if (index >= int(nbins))
509-
--index;
510-
511-
bins.at(index)++;
512-
}
503+
auto min_iter = std::min_element(values.begin(), values.end());
504+
auto max_iter = std::max_element(values.begin(), values.end());
505+
double min, max, binwidth;
506+
507+
std::vector<size_t> bins{};
508+
509+
// Check if all the elements are the same
510+
if (min_iter != max_iter) {
511+
min = *min_iter;
512+
max = *max_iter;
513+
binwidth = (max - min) / nbins;
514+
515+
bins.resize(nbins);
516+
for (const auto &val : values) {
517+
int index = static_cast<int>((val - min) / binwidth);
518+
if (index >= int(nbins))
519+
--index;
520+
521+
bins.at(index)++;
522+
}
523+
} else {
524+
// Just one bin…
525+
526+
min = max = *min_iter;
527+
binwidth = 1.0;
528+
nbins = 1;
529+
bins.push_back(static_cast<double>(values.size()));
530+
}
513531

514532
std::stringstream of;
515533
for (size_t i{}; i < nbins; ++i) {

0 commit comments

Comments
 (0)