Histograms
In this article we’ll have a look at histograms, binnings and density plots. Let’s create a simple histogram using random data:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# Let's create some random data.
data = np.random.randn(1000)
# We use the hist method to create a histogram.
fig, ax = plt.subplots()
ax.hist(data)
There are lots of arguments you can set to fine-tune your chart. You can change the number of bins, which is by default set to 10, as you can see above. The bins are of equal width. Let’s set the bin argument to some other values:
# 3 bins
fig, ax = plt.subplots()
ax.hist(data, bins=3)
# 30 bins
fig, ax = plt.subplots()
ax.hist(data, bins=30)
You can change the color of the bins:
# green color
fig, ax = plt.subplots()
ax.hist(data, color='g')
You can change the type of the histogram. To do that, you just have to set the histtype argument to one of the predefined values. By default it’s set to ‘bar’. Here it’s set to ‘step’:
# step histtype
fig, ax = plt.subplots()
ax.hist(data, histtype='step')
By default the histogram is vertical, but you can change its orientation to horizontal:
# horizontal orientation
fig, ax = plt.subplots()
ax.hist(data, orientation='horizontal')
Here’s how you can set the edge color:
# red edge
fig, ax = plt.subplots()
ax.hist(data, edgecolor='r')
If you need logarithmic scale, you can set the log argument to True:
# logarithmic scale
fig, ax = plt.subplots()
ax.hist(data, log=True)
You can also set the alpha value:
# alpha
fig, ax = plt.subplots()
ax.hist(data, alpha=.3)
As usual, check out the documentation for more options.