Graphing the Binning Example in 02.07
In 02.07, graphing the histogram using [plt.plot(bins, counts, linestyle='steps')] pops up an error. It says that 'steps' is not a valid value for linestyles.
In 02.07, graphing the histogram using [plt.plot(bins, counts, linestyle='steps')] pops up an error. It says that 'steps' is not a valid value for linestyles
You need to use matplotlib.pyplot.step instead of plot. The book currently uses an older version of matplotlib because it hasn't been updated in several years. The author is writing a new edition, but you'll run into little issues like this if you're using updated library. 🤷♂️
Full code
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
x = np.random.randn(100)
# compute a histogram by hand
bins = np.linspace(-5, 5, 20)
counts = np.zeros_like(bins)
# find the appropriate bin for each x
i = np.searchsorted(bins, x)
# add 1 to each of these bins
np.add.at(counts, i, 1)
# plot the results
# Notice that I'm calling plt.step NOT plt.plot
plt.step(bins, counts)
NumPy added a new random API since this book's last update as well. The old API is deprecated. Here is the full code using the new API.
Full code with NumPy's new random API
import numpy as np
import matplotlib.pyplot as plt
# NumPy's new random API
rng = np.random.default_rng(42)
x = rng.standard_normal(100)
# compute a histogram by hand
bins = np.linspace(-5, 5, 20)
counts = np.zeros_like(bins)
# find the appropriate bin for each x
i = np.searchsorted(bins, x)
# add 1 to each of these bins
np.add.at(counts, i, 1)
# plot the results
# Notice that I'm calling plt.step NOT plt.plot
plt.step(bins, counts)