Last active
March 3, 2022 03:18
-
-
Save hitvoice/47c63728754713d0e56eb8366bfafe56 to your computer and use it in GitHub Desktop.
Example for plotting precomputed histogram in matplotlib
This file contains hidden or 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 | |
# here's the precomputed histogram via `plt.hist` or `np.histogram` | |
bins = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).astype(float) | |
counts = np.array([5, 3, 4, 5, 6, 1, 3, 7]).astype(float) | |
assert len(bins) == len(counts) + 1 | |
# recover | |
centroids = (bins[1:] + bins[:-1]) / 2 | |
counts_, bins_, _ = plt.hist(centroids, bins=len(counts), | |
weights=counts, range=(min(bins), max(bins))) | |
plt.show() | |
# check the histogram is exactly reconstructed | |
assert np.allclose(bins_, bins) | |
assert np.allclose(counts_, counts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment