概率质量函数(PMF):使用matplotlib.pyplot.plot将概率绘制为列

时间:2019-06-27 18:53:31

标签: python matplotlib plot probability

尝试使用“ matplotlib.pyplot”将离散事件概率绘制为PMF图中的列。我希望可以使用drawstyle =“ steps-pre”通过'plot'实现我的目标,而不是'hist'函数的复杂逻辑:

def plot_pmf(self):
    """" Plot PMF """
    x,y = list(self.pmf_v.keys()), list(self.pmf_v.values())
    #_=plt.plot(x,y, marker='.', linestyle='none') # plot with dots
    _=plt.plot(x,y, drawstyle="steps-pre") # plot with columns?
    _=plt.margins(0.02)
    _=plt.title(self.title)
    _=plt.xlabel(self.x_label)
    _=plt.ylabel(self.y_label)
    plt.show()

如虹膜数据所示,这不起作用:

x = setosa["sepal_length"]
sf = StatsFun(x,"Setosa Sepal Length","length", "probability")
pmf = sf.pmf()
print(pmf)
sf.plot_pmf()

{5.1: 0.16, 4.9: 0.08, 4.7: 0.04, 4.6: 0.08, 5.0: 0.16, 5.4: 0.1, 4.4: 0.06, 4.8: 0.1, 4.3: 0.02, 5.8: 0.02, 5.7: 0.04, 5.2: 0.06, 5.5: 0.04, 4.5: 0.02, 5.3: 0.02}

enter image description here

请告知如何使用“绘图”功能获得与“ plt.hist(data,weights = weights,bins = 100)”创建的下图类似的结果,并且仅由于“ bins = 100”而有效:

data = setosa["sepal_length"]
weights = np.ones_like(np.array(data))/float(len(np.array(data)))
print(weights, sum(weights))
#plt.hist(data, bins = 100) # does the same as next line
plt.hist(data, weights=weights, bins = 100)
plt.show()

[0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02
 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02
 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02
 0.02 0.02 0.02 0.02 0.02 0.02 0.02 0.02] 1.0000000000000004

enter image description here

1 个答案:

答案 0 :(得分:0)

您的示例数据(x,y)对:

data = {5.1: 0.16, 4.9: 0.08, 4.7: 0.04, 4.6: 0.08,
        5.0: 0.16, 5.4: 0.1, 4.4: 0.06, 4.8: 0.1,
        4.3: 0.02, 5.8: 0.02, 5.7: 0.04, 5.2: 0.06,
        5.5: 0.04, 4.5: 0.02, 5.3: 0.02}

为从(x,0)到(x,y)的每对(x,y)画一条线:

for x,y in data.items():
    plt.plot((x,x),(0,y))
plt.show()
plt.close()

plotimage


如果所有行都相同,请指定颜色。

plt.plot((x,x),(0,y), 'black')