hist()函数的用法
时间: 2023-05-30 21:08:02 浏览: 70
hist()函数是matplotlib.pyplot库中用于绘制直方图的函数,其语法格式如下:
```python
matplotlib.pyplot.hist(x, bins=None, range=None, density=False, weights=None, cumulative=False, bottom=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=False, color=None, label=None, stacked=False, **kwargs)
```
参数说明:
- x:输入数据,可以是一维数组或序列。
- bins:直方图的箱子数量或指定箱子的边缘。
- range:直方图的数据范围,可以是一个元组或列表,指定数据的最小值和最大值。
- density:如果为True,则将直方图标准化为密度直方图,即直方图的面积等于1。
- weights:每个数据点的权重数组,用于加权直方图。
- cumulative:如果为True,则绘制累积直方图。
- bottom:直方图的底部位置。
- histtype:直方图的类型,包括‘bar’、‘barstacked’、‘step’、‘stepfilled’。
- align:直方图的对齐方式,包括‘left’、‘mid’、‘right’。
- orientation:直方图的方向,包括‘horizontal’、‘vertical’。
- rwidth:直方图箱子的宽度比例。
- log:如果为True,则绘制对数直方图。
- color:直方图的颜色。
- label:直方图的标签。
- stacked:如果为True,则绘制堆积直方图。
- kwargs:其他关键字参数。
示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成随机数据
np.random.seed(123)
data = np.random.normal(size=1000)
# 绘制直方图
plt.hist(data, bins=30, density=True, alpha=0.5, color='steelblue')
# 添加标题和标签
plt.title('Histogram of Random Data')
plt.xlabel('Value')
plt.ylabel('Density')
plt.show()
```
输出结果:
![histogram](https://img-blog.csdn.net/20180314153819205?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYmFpZHUxOTky/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/85)