使用np.linspace()绘制离散分布图 [英] Plot Discrete Distribution using np.linspace()
本文介绍了使用np.linspace()绘制离散分布图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用matplotlib绘制简单的离散分布:
I'm trying to plot a simple discrete distribution using matplotlib:
- 如果-1< = x< 0,p = 0.3;
- 如果0 <= x <1,p = 0.5;
- 如果1 <= x <= 2,则p = 0.2.
如何从x = np.linspace(-1, 2)
开始?
到目前为止,我尝试过的是:
What I tried so far is:
def mapDiscProb(x):
if np.any(x < 0):
return 0.3 + x * 0
elif np.any(x >= 1):
return 0.2 + x * 0
else:
return 0.5 + x * 0
x = np.linspace(-1, 2)
y = mapDiscProb(x4)
ax.plot(x, y, clip_on = False)
结果只是从-1到2的整条线,从0.3到elif
和else
都没有计算.
And the outcome is just a whole line at 0.3 from -1 to 2 as if the elif
and else
are not excuted.
我的预期输出是三个断开的水平线,这是离散pmf的标准.
My expected output is three disconnected horizontal lines, as is standard for a discrete pmf.
推荐答案
如果您只想为该示例执行此操作,则应该可以使用
If you just want to do it for that example, this should work
import numpy as np
from matplotlib import pyplot as plt
x=np.linspace(-1,2)
plt.plot(x[x < 0], 0.3 + x[x < 0]*0, color='blue')
plt.plot(x[(x >= 0) & (x <= 1)], 0.5 + x[(x>=0) & (x<=1)]*0, color='blue')
plt.plot(x[x > 1],0.2 + x[x > 1]*0, color='blue')
plt.show()
对于离散函数,屏蔽是我的解决方法.
masking is my way to go when it comes to discrete functions.
这篇关于使用np.linspace()绘制离散分布图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文