diff --git a/cmeutils/plotting.py b/cmeutils/plotting.py index 36afee1..8680a67 100644 --- a/cmeutils/plotting.py +++ b/cmeutils/plotting.py @@ -29,9 +29,9 @@ def get_histogram(data, normalize=False, bins="auto", x_range=None): Array of the bin height values """ - bin_heights, bin_borders = np.histogram(data, bins=bins, range=x_range) - if normalize is True: - bin_heights = bin_heights / sum(bin_heights) + bin_heights, bin_borders = np.histogram( + a=data, bins=bins, range=x_range, density=normalize + ) bin_widths = np.diff(bin_borders) bin_centers = bin_borders[:-1] + bin_widths / 2 return bin_centers, bin_heights diff --git a/cmeutils/tests/test_plotting.py b/cmeutils/tests/test_plotting.py index 3fa1efc..b67887c 100644 --- a/cmeutils/tests/test_plotting.py +++ b/cmeutils/tests/test_plotting.py @@ -14,6 +14,9 @@ def test_histogram_normalize(self): sample = np.random.randn(100) * -1 bin_c, bin_h = get_histogram(sample, normalize=True) assert all(bin_h <= 1) + bin_width = bin_c[1] - bin_c[0] + area = np.sum(bin_h * bin_width) + assert np.allclose(area, 1.0, atol=1e-3) def test_3dplot(self): x = [1, 2, 3, 4, 5] diff --git a/cmeutils/tests/test_structure.py b/cmeutils/tests/test_structure.py index 3e9e077..d57eb40 100644 --- a/cmeutils/tests/test_structure.py +++ b/cmeutils/tests/test_structure.py @@ -136,7 +136,8 @@ def test_bond_dist_normalize(self, p3ht_gsd): histogram=True, normalize=True, ) - assert np.allclose(np.sum(bonds_hist[:, 1]), 1, 1e-3) + bin_width = bonds_hist[:, 0][1] - bonds_hist[:, 0][0] + assert np.allclose(np.sum(bonds_hist[:, 1] * bin_width), 1, 1e-3) def test_bond_range_outside(self, p3ht_gsd): with pytest.warns(UserWarning): @@ -172,7 +173,8 @@ def test_angle_dist_normalize(self, p3ht_gsd): histogram=True, normalize=True, ) - assert np.allclose(np.sum(angles_hist[:, 1]), 1, 1e-3) + bin_width = angles_hist[:, 0][1] - angles_hist[:, 0][0] + assert np.allclose(np.sum(angles_hist[:, 1] * bin_width), 1, 1e-3) def test_angle_range_outside(self, p3ht_gsd): with pytest.warns(UserWarning):