Plot Piecewise Function in Python

后端 未结 5 474
[愿得一人]
[愿得一人] 2021-01-02 10:56

I would like to plot the following piecewise function in Python using Matplotlib, from 0 to 5.

f(x) = 1, x != 2; f(x) = 0, x = 2

In Python...

5条回答
  •  遥遥无期
    2021-01-02 11:36

    Some answers are starting to get there... But the points are being connected into a line on the plot. How do we just plot the points?

    import matplotlib.pyplot as plt
    import numpy as np
    
    def f(x):
     if(x == 2): return 0
     else: return 1
    
    x = np.arange(0., 5., 0.2)
    
    y = []
    for i in range(len(x)):
       y.append(f(x[i]))
    
    print x
    print y
    
    plt.plot(x,y,c='red', ls='', ms=5, marker='.')
    ax = plt.gca()
    ax.set_ylim([-1, 2])
    
    plt.show()
    

提交回复
热议问题