【发布时间】:2014-03-02 12:51:35
【问题描述】:
我有整数列表,想获取每个整数的频率。这是讨论here
问题是当我的数据集仅包含整数时,我使用的方法给了我浮点数的频率。为什么会发生这种情况以及如何从数据中获取整数频率?
我正在使用 pyplot.histogram 绘制具有出现频率的直方图
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
data = loadtxt('data.txt',dtype=int,usecols=(4,)) #loading 5th column of csv file into array named data.
plt.hist(data) #plotting the column as histogram
我正在获取直方图,但我注意到如果我“打印” hist(data)
hist=np.histogram(data)
print hist(data)
我明白了:
(array([ 2323, 16338, 1587, 212, 26, 14, 3, 2, 2, 2]),
array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. , 11.8, 13.6, 15.4,
17.2, 19. ]))
其中第二个数组表示值,第一个数组表示出现次数。
在我的数据集中,所有值都是整数,第二个数组有浮点数是如何发生的,我应该如何获得整数的频率?
更新:
这样就解决了问题,谢谢Lev的回复。
plt.hist(data, bins=np.arange(data.min(), data.max()+1))
为避免产生新问题,我如何为每个整数绘制“中间”列?比如说,我希望整数 3 的列在 2.5 和 3.5 之间而不是在 3 和 4 之间。
【问题讨论】:
-
您确定您使用的是您认为的数据吗?您的评论说第 4 列,但索引从 0 开始,所以第 4 列实际上是第 5 列。
-
是的,这是第五栏,错字。
-
我猜应该是
data.max() + 2。np.arange没有上边框,bins包含范围(元素从 0-1、1-2、...)
标签: python matplotlib