玩命加载中...
### 5. plt.hist直方图
掌握了上面一些通用的技巧之后,我们可以很快地学习制作其他类型的图像。直方图是一种常用来近似显示数值分布的图像。
我们可以直接调用`plt.hist(x)`。
```python
import numpy as np
x = np.random.normal(0, 1, 1000)
plt.figure(figsize=(5, 3))
plt.hist(x)
plt.show()
```

`plt.hist`中的参数`bins`用来设定直方图中分组的数量。下图例子中我们设定`bins=5`。
```python
plt.figure(figsize=(5, 3))
plt.hist(x, bins=5)
plt.show()
```

`bins`是非常灵活的参数,我们可以将`bins`设定为一个`list`或者`numpy.ndarray`的形式。这样的话,直方图就会按照`list`中的元素,划定每个bin的上下界。示例如下:
```python
plt.figure(figsize=(5, 3))
plt.hist(x, bins=[-4, -2, -1, -0.5, 0, 0.5, 2, 5])
plt.show()
```

与`plt.plot`一样,我们也可以为`plt.hist`设定颜色`c`,线宽`lw`,透明度`alpha`等参数。
```python
plt.figure(figsize=(5, 3))
plt.hist(x, color='g', lw=0.2, alpha=0.5)
plt.show()
```

同样我们可以通过`plt.title, plt.legend, plt.xlabel, plt.ylabel`等给直方图添加注释。
```python
plt.figure(figsize=(5, 3))
num_bins = 12
plt.hist(x, bins=num_bins, color='g', lw=0.2, alpha=0.5, label='counts')
plt.legend()
plt.title('My %s-bin histogram.'%num_bins)
plt.xlabel('This is x-axis')
plt.ylabel('This is y-axis')
plt.show()
```
