Created
August 27, 2022 16:54
-
-
Save 338rajesh/e4b3039ccddc697b70a5a2cac9cd430d to your computer and use it in GitHub Desktop.
It clips the histogram by minimum frequency
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import matplotlib.pyplot as plt | |
def clip_histogram(data, get_indices=False, **hist_kwargs): | |
n, bns = np.histogram(data, **hist_kwargs) | |
bin_pairs = [(bns[i], bns[i+1]) for i in range(len(bns)-1)] | |
new_data = [] | |
indices = [] | |
for (i, (bnl, bnu)) in enumerate(bin_pairs): | |
bin_width = bnu - bnl | |
ith_bin_values = [] | |
for (idx, v) in enumerate(data): | |
if (bnl < v < bnu) and (len(ith_bin_values) < min(n)): | |
ith_bin_values.append(v) | |
indices.append(idx) | |
# | |
new_data += ith_bin_values | |
# | |
return (new_data, indices) if get_indices else new_data | |
N = 1000 | |
a = np.random.randn(N) | |
hist_kwargs = {"bins": 24, "range": (0.0, 1.0)} | |
a_clipped = clip_vals(a, **hist_kwargs) | |
plt.figure(figsize=(20, 10)) | |
plt.subplot(1, 2, 1) | |
plt.hist(a, **hist_kwargs) | |
plt.subplot(1, 2, 2) | |
plt.hist(a_clipped, **hist_kwargs) | |
plt.show() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment