特别是作为初学者,尽量保持简单。你有一个数字列表
a = [-0.126,1,9,72.3,-44.2489,87.44]
你想创建一个直方图,为此需要定义一些区间。假设你想将-180到180的范围分成宽度为20的区间,
import numpy as np
bins = np.arange(-180,181,20)
你可以使用
numpy.histogram
计算直方图,它会返回每个区间内的计数。
hist, edges = np.histogram(a, bins)
相对频率是每个区间内事件数量与总事件数的比值。
freq = hist/float(hist.sum())
因此,数量freq
是您想要绘制为条形图的相对频率。
import matplotlib.pyplot as plt
plt.bar(bins[:-1], freq, width=20, align="edge", ec="k" )
这导致了以下图表,您可以从中读出例如33%的值位于0到20的范围内。
![enter image description here](https://istack.dev59.com/xUlLJ.webp)
完整代码:
import numpy as np
import matplotlib.pyplot as plt
a = [-0.126,1,9,72.3,-44.2489,87.44]
bins = np.arange(-180,181,20)
hist, edges = np.histogram(a, bins)
freq = hist/float(hist.sum())
plt.bar(bins[:-1],freq,width=20, align="edge", ec="k" )
plt.show()
df = pd.DataFrame({'number': [1,2,3,4,5,6], 'angle': [-0.126, 1, 9, 72.3, -44.2489, 87.44]})
。 - 3novak