如何绘制不均匀数据点之间具有均匀间隔的直方图?

时间:2018-08-04 08:18:18

标签: python python-3.x matplotlib plot bar-chart

因此,我有一个数组y,包含2的幂,例如1、2、4、8、16,...,我想将它们放在直方图中以查看每个出现的次数。但是当我绘制它们时,结果却是这样的:enter image description here

我的问题是:我如何将它们紧靠在一起,并以1,2,4,8,...全部均匀分布,而不是像这样进一步将32和64隔开。我的示例代码是:

import matplotlib.pyplot as plt

y=(2,1,8,1,64,8,2,8,32,0)

plt.hist(y,bins=128)
plt.xlabel('Power of 2')
plt.ylabel('Number of times show up')
plt.show()

谢谢!

1 个答案:

答案 0 :(得分:1)

显示唯一数字

您可以将numpy.unique与参数return_counts一起使用。然后将这些计数绘制为索引的函数(例如,使用条形图),并用唯一的数字标记刻度线。

import numpy as np
import matplotlib.pyplot as plt

y=(2,1,8,1,64,8,2,8,32,0)

u, counts = np.unique(y, return_counts=True)

plt.bar(np.arange(len(u)), counts)
plt.xticks(np.arange(len(u)), u)
plt.xlabel('Power of 2')
plt.ylabel('Number of times show up')
plt.show()

enter image description here

显示2的所有幂

如果要显示2的所有幂,即使那些未出现在输入值列表中的幂,解决方案也比较棘手。特别是由于列表中有0,而不是2的幂。

一个人可以在这里使用循环,并用计数中的值填充一个新数组。

import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict

y=(2,1,8,1,64,8,2,8,32,0)

u, counts = np.unique(y, return_counts=True)
lookup = defaultdict(int, zip(u, counts))
maxpow = np.log2(np.max(y))
print maxpow
complete = np.concatenate(([0], 2**np.arange(0,maxpow)))
complete_counts = np.zeros_like(complete)
for i, p in enumerate(complete):
    complete_counts[i] = lookup[p]

plt.bar(np.arange(len(complete)), complete_counts)
plt.xticks(np.arange(len(complete)), complete)
plt.xlabel('Power of 2')
plt.ylabel('Number of times show up')
plt.show()

enter image description here