matplotlib密度图/直方图

时间:2019-02-13 17:41:38

标签: python arrays matplotlib graph histogram

我有一个数组:[0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1,1](16个长) 如何使用例如bins = 4来创建密度直方图,以查看出现最多1:s的位置?例如,此直方图在中间部分会很高,而在末尾会稍微升高(在开始和结束时最多为1:s)。 我有这个:

plt.hist([0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1], bins=4)

This is what i get。该直方图仅表明它的1:s与0:s一样多。

以后如何创建图形(线)以显示直方图的平均上升和下降?

2 个答案:

答案 0 :(得分:0)

直方图不会评估您的值的位置;它表示数据的分布,历史值的位置无关紧要;最小值和最大值表示数据的最小值和最大值。 我会尝试设置一个索引并将其用作您的范围。

我认为这是与您描述的图形最接近的答案: Pandas bar plot with binned range 在这里,BeingOfBeingEnrnest的答案也可能会有所帮助。

Plot a histogram using the index as x-axis labels

答案 1 :(得分:0)

我不会将其称为直方图。它更多是空间密度图。 因此,您可以枚举列表,以使第一个元素的编号为0,最后一个元素的编号为15。然后将此列表划分为4个bin。在每个容器中,您可以计算一次看到1的频率。要使其自动化,可以选择scipy.stats.binned_statistic

import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import binned_statistic

data = [0,0,0,0,0,1,1,1,1,1,0,0,0,1,1,1]
x = np.arange(len(data))

s, edges, _ = binned_statistic(x, data, bins=4, statistic = lambda c: len(c[c==1]))
print(s, edges)
plt.bar(edges[:-1], s, width=np.diff(edges), align="edge", ec="k")
plt.show()

因此,这里的边是[0., 3.75, 7.5, 11.25, 15.],每个箱中的1的数目是[0. 3. 2. 3.]

enter image description here