Skip to content

Instantly share code, notes, and snippets.

@hitvoice
Last active March 3, 2022 03:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hitvoice/47c63728754713d0e56eb8366bfafe56 to your computer and use it in GitHub Desktop.
Save hitvoice/47c63728754713d0e56eb8366bfafe56 to your computer and use it in GitHub Desktop.
Example for plotting precomputed histogram in matplotlib
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