matplotlib.pyplot中的hist函数简单使用

今天学习直方图绘制,使用了hist函数绘制直方图。

首先看官网定义:

matplotlib.pyplot.hist(xbins=Nonerange=Nonenormed=Falseweights=Nonecumulative=Falsebottom=Nonehisttype='bar'align='mid'orientation='vertical'rwidth=Nonelog=Falsecolor=Nonelabel=Nonestacked=Falsehold=Nonedata=None**kwargs)

Plot a histogram.

Compute and draw the histogram of x. The return value is a tuple (nbinspatches) or ([n0n1, ...], bins, [patches0patches1,...]) if the input contains multiple data.

Multiple data can be provided via x as a list of datasets of potentially different length ([x0x1, ...]), or as a 2-D ndarray in which each column is a dataset. Note that the ndarray form is transposed relative to the list form.

这里先解释直方图(histogram)是什么?

 直方图是为了表明数据分布情况。通俗地说就是哪一块数据所占比例或者出现次数较高,哪一块出现概率低。如下图


横轴是数据,纵轴是出现的次数(也就是频数)。从这个图看4.1-4.3这块数据出现次数最高。

扫描二维码关注公众号,回复: 1996563 查看本文章

从上面可以看出直方图能够反映数据的分布状况。

在matplotlib中,我们使用hist函数完成直方图的绘制。(这里仅仅介绍最简单的使用方法,更多扩展请官网查询)

首先构造数据,这里注意构造的是一维数组可以使用pandas中的Series,如果是二维数组使用DataFrame。

import pandas as pd
import numpy as np
import random
data = np.zeros((1000,1000),dtype=int)
for i in range(len(data)):#这里速度比较慢,因为随机给1000*1000的数组赋值
    for j in range(len(data[0])):
        data[i][j] = random.randint(1,20)#赋值的范围是1-20中的任意一个
data_m = pd.DataFrame(data)
data_m = data_m[1].value_counts()#注意value_counts函数统计一个series上的数据情况
data_m = data_m.sort_index()#给统计后的数据排序
print data_m

运行结果(左边是数据,右边是频数,按照数据的大小来排序)

1     55
2     49
3     51
4     42
5     51
6     38
7     44
8     55
9     41
10    56
11    45
12    43
13    51
14    54
15    46
16    53
17    56
18    52
19    62
20    56
Name: 1, dtype: int64



随后开始画直方图:

import matplotlib.pyplot as plt
plt.hist(data[0])
plt.show()

运行结果



默认情况下,总共分为10段,可以数一下上面的段数。如果使用如下代码:

import matplotlib.pyplot as plt
plt.hist(data[0],bins=20)
plt.show()

运行结果:


可以看出效果更明显。根据自己的需要进行选择!!



猜你喜欢

转载自blog.csdn.net/u014525494/article/details/80157402