Skip to content

Instantly share code, notes, and snippets.

@hanvari
Last active March 13, 2022 20:06
Show Gist options
  • Save hanvari/462b0613e56c901a9420f5a22a9dd386 to your computer and use it in GitHub Desktop.
Save hanvari/462b0613e56c901a9420f5a22a9dd386 to your computer and use it in GitHub Desktop.
Plotting Histogram In Python

Plotting Histograms in Python

Using MatPlotLib API

Example 1:

s = np.random.uniform(-1,0,1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 15, normed=True)
plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
plt.show()

Reference: https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.uniform.html

Example 2:

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

Reference: https://stackoverflow.com/a/43822468

Using NumPy API

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

Using Object-oriented

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

Reference: https://stackoverflow.com/a/5328669

@rawstar134
Copy link

I found the very best article to create a histogram with python. Download code with explanation

@hanvari
Copy link
Author

hanvari commented Mar 13, 2022

I found the very best article to create a histogram with python. Download code with explanation

Thank you for sharing that link, but the intended use for this gist (generating histogram for an array of numbers) is completely different from the link you shared (which generates a histogram for an image).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment