How to plot a branched sin(x) function

I’m a noob practicing how to use pylab, matplot lib etc.

Somehow I’m not able to plot this simple branched sin(x) function in pylab/matplotlib.

from math import sin
import pylab as plb

def f(x):
    if sin(x) > 0:
        return sin(x)
    else:
        return 0

x = plb.linspace(-4,4,10000)

plb.plot(x,f(x))
plb.show()

The following error outputs when I run the program:

Traceback (most recent call last):
  File "C:/Users/...plot.py", line 12, in <module>
    plb.plot(x,f(x))
  File "C:/Users/......plot.py", line 5, in f
    if sin(x) > 0:
TypeError: only size-1 arrays can be converted to Python scalars

Is there anyone who can help me out?

Answer

The inbuilt sine function inside math module accepts only a scalar value. You can use numpy sine instead to accomplish your plot as it accepts an array.

import numpy as np
import pylab as plb


def f(x):
    sine_ =  np.sin(x)
    sine_[sine_< 0] = 0
    return sine_
    
x = plb.linspace(-4,4,10000)

plb.plot(x,f(x))
plb.show()

The output is as shown below:

[enter image description here]

However, as pointed out by Trenton McKinney, this answer states the use of pylab is no longer recommended. So, the alternate solution using matplotlib.pyplot is shown below:

import numpy as np
import matplotlib.pyplot as plt


def f(x):
    sine_ =  np.sin(x)
    sine_[sine_< 0] = 0
    return sine_
    
x = np.linspace(-4,4,10000)

plt.plot(x,f(x))
plt.show()

The output is the same as the image above.