在Python中绘制直方图
我有两个列表,x和y。
x里包含了字母A到Z,而y里则是这些字母在一个文件中出现的频率。
我试着查找如何把这些值画成直方图,但一直没能理解怎么画。
n, bins, patches = plt.hist(x, 26, normed=1, facecolor='blue', alpha=0.75)
那x是不是上面提到的列表x呢?
1 个回答
50
hist
是用来处理一组数值的,它会计算这些数值的频率并绘制出直方图。在你的情况中,你已经提前计算好了每个组(字母)的频率。为了更好地用直方图的形式展示你的数据,建议使用 matplotlib 的 bar
函数:
import numpy as np
import matplotlib.pyplot as plt
alphab = ['A', 'B', 'C', 'D', 'E', 'F']
frequencies = [23, 44, 12, 11, 2, 10]
pos = np.arange(len(alphab))
width = 1.0 # gives histogram aspect to the bar diagram
ax = plt.axes()
ax.set_xticks(pos + (width / 2))
ax.set_xticklabels(alphab)
plt.bar(pos, frequencies, width, color='r')
plt.show()