Plot Discrete Distribution using np.linspace()

后端 未结 2 1487
Happy的楠姐
Happy的楠姐 2021-01-29 04:59

I\'m trying to plot a simple discrete distribution using matplotlib:

  • If -1<=x<0, p=0.3;
  • If 0<=x<1, p=0.5;
  • If 1<=x<=2, p=0.2.
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 05:47

    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.

提交回复
热议问题