So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing
JavaScript
x
2
1
bins, n=hist()
2
but it didn’t like that. Any recommendations?
Advertisement
Answer
JavaScript
1
11
11
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
mu, sigma = 100, 15
5
x = mu + sigma * np.random.randn(10000)
6
hist, bins = np.histogram(x, bins=50)
7
width = 0.7 * (bins[1] - bins[0])
8
center = (bins[:-1] + bins[1:]) / 2
9
plt.bar(center, hist, align='center', width=width)
10
plt.show()
11
The object-oriented interface is also straightforward:
JavaScript
1
4
1
fig, ax = plt.subplots()
2
ax.bar(center, hist, align='center', width=width)
3
fig.savefig("1.png")
4
If you are using custom (non-constant) bins, you can pass compute the widths using np.diff
, pass the widths to ax.bar
and use ax.set_xticks
to label the bin edges:
JavaScript
1
17
17
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
mu, sigma = 100, 15
5
x = mu + sigma * np.random.randn(10000)
6
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
7
hist, bins = np.histogram(x, bins=bins)
8
width = np.diff(bins)
9
center = (bins[:-1] + bins[1:]) / 2
10
11
fig, ax = plt.subplots(figsize=(8,3))
12
ax.bar(center, hist, align='center', width=width)
13
ax.set_xticks(bins)
14
fig.savefig("/tmp/out.png")
15
16
plt.show()
17