绘制连音符matplotlib列表的直方图

时间:2016-01-29 12:27:12

标签: python matplotlib

我有一个连音符列表

k = [(8, 8),(10, 10),(8, 8),
 (8, 8),(12, 12),(7, 7),(8, 8),
 (9, 9),(10, 10),(10, 10),(8, 8),(9, 9),(13, 13),
 (10, 10),(8, 8),(8, 8),(7, 7)]

我想对每个连音符的频率做一个简单的直方图。怎么会这样做呢?

标准plt.dist似乎没有用,也没有将连音符重新映射到单个变量。

1 个答案:

答案 0 :(得分:3)

直方图(numpy.histplt.hist)通常位于连续数据上,您可以轻松地在分档中分隔。

在这里,您要计算相同的元组:您可以使用collection.Counter

from collections import Counter
k = [(8, 8),(10, 10),(8, 8),
 (8, 8),(12, 12),(7, 7),(8, 8),
 (9, 9),(10, 10),(10, 10),(8, 8),(9, 9),(13, 13),
 (10, 10),(8, 8),(8, 8),(7, 7)]

c=Counter(k)
>>> Counter({(8, 8): 7, (10, 10): 4, (9, 9): 2, (7, 7): 2, (13, 13): 1, (12, 12): 1})

经过一些格式化后,您可以使用plt.bar以直方图方式绘制每个元组的计数。

# x axis: one point per key in the Counter (=unique tuple)
x=range(len(c))
# y axis: count for each tuple, sorted by tuple value
y=[c[key] for key in sorted(c)]
# labels for x axis: tuple as strings
xlabels=[str(t) for t in sorted(c)]

# plot
plt.bar(x,y,width=1)
# set the labels at the middle of the bars
plt.xticks([x+0.5 for x in x],xlabels)

tuple bar plot