Show Sidebar Hide Sidebar

Histograms in matplotlib

How to make a histogram in matplotlib. Seven examples of colored, horizontal, and normal histogram bar charts.

import matplotlib.pyplot as plt
import numpy as np

import plotly.plotly as py
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

gaussian_numbers = np.random.randn(1000)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")

fig = plt.gcf()

plot_url = py.plot_mpl(fig, filename='mpl-basic-histogram')
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

import pylab as plt
import plotly.plotly as py

fig = plt.figure()

x = 200 + 25*plt.randn(1000)
y = 150 + 25*plt.randn(1000)
n, bins, patches = plt.hist([x, y])

plot_url = py.plot_mpl(fig, filename='docs/mpl-histogram')
Inspired by Stack Overflow.
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

import random
import numpy
import matplotlib.pyplot as plt
import plotly.plotly as py  # tools to communicate with Plotly's server

histogram=plt.figure()

x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]

bins = numpy.linspace(-10, 10, 100)

pyplot.hist(x, bins, alpha=0.5)
pyplot.hist(y, bins, alpha=0.5)
pyplot.show()

plot_url = py.plot_mpl(histogram, filename='docs/histogram-mpl-same')
Inspired by Stack Overflow.
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import plotly.plotly as py  # tools to communicate with Plotly's server

fig = plt.figure()

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)

num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)

plot_url = py.plot_mpl(fig, filename='docs/histogram-mpl-legend')
Inspired by matplotlib gallery.
# Learn about API authentication here: https://plot.ly/python/getting-started
# Find your api_key here: https://plot.ly/settings/api

import matplotlib.pyplot as plt
import numpy as np
import plotly.plotly as py  # tools to communicate with Plotly's server

numpy_hist = plt.figure()

plt.hist([1, 2, 1], bins=[0, 1, 2, 3])

plot_url = py.plot_mpl(numpy_hist, filename='numpy-bins')
Inspired by Stack Overflow.
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.